I am using cURL and REST to access a database and a query search, i am getting the following response when i use echo $response:
HTTP/1.1 200 OK Date: Fri, 05 Aug 2016 06:53:02 GMT Server: Apache Content-Language: en-US RNT-Time: D=58292 t=1470379982660626 RNT-Machine: 128.65 Transfer-Encoding: chunked Content-Type: application/json { "items": [ { "tableName": "Country", "count": 1, "columnNames": [ "id" ], "rows": [ [ "12" ] ] } ], "links": [ { "rel": "self", "href": "https://test.cust.com/services/rest/connect/v1.3/queryResults?query=select%20ID%20from%20CO.Country%20where%20CO.Country.Country=%27USA%27" }, { "rel": "canonical", "href": "https://test.cust.com/services/rest/connect/v1.3/queryResults" }, { "rel": "describedby", "href": "https://test.cust.com/services/rest/connect/v1.3/metadata-catalog/queryResults", "mediaType": "application/schema+json" } ] }
i tried to use JSON_decode() but so far i got nowhere, how can i get my parameters here ? to be more specific, the "id" value.
If I get you right you have 2 options:
turn off receiving headers curl_setopt($ch, CURLOPT_HEADER, 0)
break your response by \r\n\r\n, you'll get header and body
list($header, $body) = explode("\r\n\r\n", $response, 2)
The response which posted here is seems like server response sending to the client browser,
so, you have few of options to parse this data
In case of this response must be parsed using PHP then you can try parsing data using parse_str() in PHP by following way.
if (FALSE !== (stripos($response, '{'))) {
$data = trim(substr($response, stripos($response, '{')));
$data_arr = array();
parse_str($data, $data_arr);
print_R($data_arr);
//Digging down using parse_str() in php
} else {
echo "No data found.";
}
Either use client side javascript/jquery/client side script to parse json from response on browser.
Returning header as array using Curl
You don't need to use JSON_decode().
Use:
$obj = $_POST['items']; // for post
for get:
$obj = $_GET['items'];
With the help of #evilive, i was able to get it to work:
1- turn of receiving headers curl_setopt($ch, CURLOPT_HEADER, 0)
2- $test=$res->items[0]->rows[0];
echo $test[0];
$response;//Suppose your respond is this.
$obj = json_decode($response);
Then you can access your parameters.
Example:
$obj-> items
Related
I am having trouble with the response from Companies House API. I am making the following curl request from a php page:
$request_url_1 ='https://api.companieshouse.gov.uk/company/' ;
$company_number = 11495745;
$request_url_2 = '/officers';
$request_url = $request_url_1 . $company_number . $request_url_2;
$ch = curl_init($request_url);
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '. base64_encode("$chkey:")
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$content = curl_exec($ch);
curl_close( $ch );
$contents = json_decode($content,true);
The following is the response that is 'pasted' on the php page after sending the curl request, and I cannot seem to get at the contents/value of the $contents variable that should contain the curl response.
{
"active_count":1,
"items_per_page":35,
"kind":"officer-list",
"etag":"6cc48213158205c9fa85492a4c2ef0a98b56b2f1",
"resigned_count":2,
"items":[
{
"date_of_birth":{
"year":1963,
"month":2
},
"appointed_on":"2019-08-01",
"nationality":"British",
"address":{
"address_line_1":"Moorside Crescent",
"country":"United Kingdom",
"address_line_2":"Sinfin",
"postal_code":"DE24 9PH",
"locality":"Derby",
"premises":"75"
},
"occupation":"Company Director",
"links":{
"officer":{
"appointments":"/officers/IryiaaBZodlGNaOP0Rf3Pb2GnO8/appointments"
}
},
"name":"MILLER, Eira",
"country_of_residence":"England",
"officer_role":"director"
},
{
"date_of_birth":{
"month":3,
"year":1987
},
"nationality":"English",
"occupation":"Company Director",
"address":{
"locality":"Derby",
"address_line_1":"Moorside Crescent",
"premises":"75",
"country":"United Kingdom",
"postal_code":"DE24 9PH",
"address_line_2":"Sinfin"
},
"appointed_on":"2018-12-10",
"resigned_on":"2019-07-31",
"name":"KING, Kimberley Rachel",
"links":{
"officer":{
"appointments":"/officers/av7G3-iF_9-FXhRH2xm-IxejeGQ/appointments"
}
},
"country_of_residence":"United Kingdom",
"officer_role":"director"
},
{
"address":{
"postal_code":"DE24 9PH",
"locality":"Derby",
"country":"United Kingdom",
"premises":"75",
"address_line_2":"Sinfin",
"address_line_1":"Moorside Crescent"
},
"occupation":"Managing Director",
"nationality":"British",
"appointed_on":"2018-08-01",
"resigned_on":"2018-12-10",
"officer_role":"director",
"country_of_residence":"United Kingdom",
"links":{
"officer":{
"appointments":"/officers/X9nlVD6qIIENMjaH946__4CB3QE/appointments"
}
},
"name":"MARTIN, Katey",
"date_of_birth":{
"month":6,
"year":1968
}
}
],
"links":{
"self":"/company/11495745/officers"
},
"inactive_count":0,
"start_index":0,
"total_results":3
}
I have tried returning result as non-associative array and access it through normal array but no joy there either.
FluffyKitten kindly supplied the following code to perform the extraction of the name field:
$item = $contents["items"];
foreach($item as $items){
echo $items["name"];
}
However, this couldn't access the required data. A print_r of $contents results in '1' and a var_dump (1)
There are a couple of problem with your code:
You are mixing up code for accessing arrays and objects
You are looping when there is no need for loops
You are using json_decode($content,true), and by passing in that true parameter, you are converting the result into associative arrays, but then you try to access items as the property of an object.
Because you have converted the contents to an associative array, you can easily access the information you want using the correct keys, e.g.:
$item = $contents["items"];
foreach($item as $items){
echo "<p>".$items["name"];
}
Reference PHP json_decode Documentation
UPDATE:
Your question has changed totally - it was about how to loop through the variable with the results, but now it seems that the problem is saving the results as a variable in the first place.
You need to set the CURLOPT_RETURNTRANSFER option to true so that the result is not output directly (I assume this is what you mean by the result being "pasted" into the PHP page).
Add this to your CURL code, and if the rest of your code is correct, the result should be saved in the $content variable so you can use it to loop through using the code above:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
I have error 400 Invalid endpoint in my code :
$this->load->library('PHPRequests');
$headers = array(
'X-CleverTap-Account-Id' => 'xxxx-xxx-xxx-xxxx',
'X-CleverTap-Passcode' => 'xxx-xxx-xxx',
'Content-Type' => 'application/json; charset=utf-8'
);
$data = '{ "d": [ { "FBID": "34322423", "ts": 1468308340, "type": "event", "evtName": "Product viewed", "evtData": { "Product name": "Casio Chronograph Watch", "Category": "Mens Watch", "Price": 59.99, "Currency": "USD" } } ] }';
$response = Requests::post('https://api.clevertap.com/1/upload', $headers, $data);
echo "<pre>";
print_r($response);
echo "</pre>";
please help me solve this problem
Have you tried the curl example using your API account credentials? My guess is you are not using the correct ones and getting the 400 error.
Once you get the CURL example working then you should be able to modify your PHP code to match.
You can find out more about the authentication here
https://developer.clevertap.com/docs/authentication
I am trying to get the response from an http request from the Hunter API.
The url is something like this :
https://api.hunter.io/v2/email-finder?domain=mydomain&api_key=myapikey&first_name=myfirstname&last_name=myname
And the response is something like this :
{
"data": {
"email": "emailfound#domain.tld",
"score": 68,
"domain": "domain.tld",
"sources": [
{
"domain": "domain.tld",
"uri": "http://somedomain.tld/",
"extracted_on": "2017-04-04"
}
]
},
"meta": {
"params": {
"first_name": "myfirstname",
"last_name": "mylastname",
"full_name": null,
"domain": "domain.tld",
"company": null
}
}
}
Here is what I am doing in my controller :
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
// return response
$json = new JsonResponse();
$datas = $json->setData($response);
return json_encode($datas);
And here is what json_encode($datas) returns :
{"headers":{}}
I precise that I am working with Symfony3 and testing on my OVH serveur (Performance offer).
Any idea where does come from this response ? and why I am not getting the real response ? Thanks !
As per my comment,
Instead of using CURL (Which is a much harder system to deal with IMO), you should use file_get_contents() like so:
$json = file_get_contents($url);
$obj = json_decode($json,true);
Try this:
$json = file_get_contents('https://api.hunter.io/v2/email-finder?domain=mydomain&api_key=myapikey&first_name=myfirstname&last_name=myname');
$data = json_encode($json,true)
var_dump($data);
I am new at REST and trying to get only the ID from the query SELECT ID from CO.A_Country where Name="xxx"; using the ROQL. I am using REST with PHP:
<?php
/**
* Example API call
* GET profile information
*/
// the ID of the profile
$profileID = 2;
// the token
$token = 'your token here';
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
"https://User:Pass#test.help.com/services/rest/connect/v1.3/queryResults
/?query=select%20ID%20from%20CO.A_Country%20where%20CO.A_Country.A_Country=%27xxx%27");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
echo($output). PHP_EOL;
curl_close($ch);
?>
I am getting the following result:
HTTP/1.1 200 OK Date: Thu, 04 Aug 2016 14:58:02 GMT Server: Apache Content-Language: en-US RNT-Time: D=58455 t=1470322682582920 RNT-Machine: 128.64 Transfer-Encoding: chunked Content-Type: application/json { "items": [ { "tableName": "CO.Affected_Country", "count": 1, "columnNames": [ "id" ], "rows": [ [ "12" ] ] } ], "links": [ { "rel": "self", "href": "https://test.help.com/services/rest/connect/v1.3/queryResults?query=select%20ID%20from%20CO.A_Country%20where%20CO.A_Country.Affected_Country=%27USA%27" }, { "rel": "canonical", "href": "https://test.help.com/services/rest/connect/v1.3/queryResults" }, { "rel": "describedby", "href": "https://test.help.com/services/rest/connect/v1.3/metadata-catalog/queryResults", "mediaType": "application/schema+json" } ] }
How to get only the desired ID to be in $output?
You cannot just get the ID from a ROQL query from the OSvC REST API; especially since your query could return multiple results. This other data will always be returned as part of your results (and other relevant data depending on the endpoint that you use). You need to parse those results to get the ID from your query.
Do not return the header as part of the response body:
curl_setopt($ch, CURLOPT_HEADER, 0);
Then use json_decode to convert the ROQL results into a PHP object, as #Manish Shukla suggests.
$results = json_decode($output);
Then, your ROQL results are parsable. Rows are returned as an array that you can loop through. Since your query doesn't have a limit statement, you should either add that or account for multiple values being returned.
if(!is_null($results['items'][0]['rows'])){
foreach($results['items'][0]['rows'] as $row){
echo $row; //Will output the ID from your select statement. Change this to do something with the ID as needed.
}
}
basically curl is returning you complete data as json. First of all convert this data to php and then you can traverse that array to find exact value.
you can use json_decode function. For further details of function please refer this.
http://php.net/manual/en/function.json-decode.php
I'm trying to read the contents of a webhook notification in php. The content of the request is in the link below:
Link POST
HEADERS:
Pragma: no-cache
X-Request-Id: fec7f2ea-ae08-4fc1-9f81-b7ed9b976100
X-Newrelic-Transaction: PxQDWVNWCgBWBlJWVldRV1dUFB8EBw8RVU4aVgANAQAAA1tSBQBVBFUFUkNKQQtVVlNTUVZQFTs=
Accept: text/html, image/gif, image/jpeg, *; q=.2, /; q=.2
Connect-Time: 2
Connection: close
Content-Length: 931
Cache-Control: no-cache
User-Agent: Java/1.7.0_72
Accept-Encoding: gzip
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Via: 1.1 vegur
X-Newrelic-Id: UgcDUFdVGwQAXFdRBAU=
Host: requestb.in
Total-Route-Time: 0
FORM/POST PARAMETERS:
data: { "event": "PAYMENT_UPDATED", "payment": { "object": "payment", "id": "pay_158657847699", "customer": "cus_artujit2nfYe", "value": 160.0, "netValue": 155.75, "originalValue": null, "nossoNumero": "34271724", "description": "", "billingType": "BOLETO", "status": "PENDING", "dueDate": "21/12/2016", "paymentDate": null, "invoiceUrl": "", "boletoUrl": "", "invoiceNumber": "00507815", "externalReference": null, "deleted": false } }
I tried unsuccessfully through the line code: $datasrc = $_POST;
I also tried to read with $ _REQUEST unsuccessfully.
How to read the content in php?
No clue what webhook is or does. But if it is sent as as POST request to a page in PHP, the data posted will be present in the $_POST array.
To see what's in it: var_dump($_POST); will show you the array and it's structure.
To get the value of a specific key: $variable = $_POST['key']; will do the trick.
If I interpret the stuff you posted correctly the json encoded content should be in $_POST['data']; .
To decode the json encoded string, PHP has helpful functions such as json_decode.
$data=json_decode($_POST['data'], true); should give you a PHP array with the data.