Trying to echo a couple of values from the CURL JSON response so i can put them in to a foreach loop but i can only get single indexed values to work.
$request = curl_init($api); // initiate curl object
curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
//curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment if you get no gateway response and are using HTTPS
curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded"
));
$response = (string)curl_exec($request); // execute curl fetch and store results in $response
curl_close($request); // close curl object
$result = json_decode($response, true); // true turns it into an array
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
echo 'Last Name: ' . $result[0]['last_name'] . '<br />'; // yet i can return the first value
Example Array output
Array
(
[0] => Array
(
[id] => 34761
[first_name] => A
[last_name] => Bailes
[clinic] =>
[phone] => 7409923279
[fax] => 7409926740
[address1] => 507 Mulberry Heights Rd
[address2] =>
[city] => Pomeroy
[subdivision] => OH
[country_code] =>
[postal_code] => 45769-9573
[timezone] => Array
(
[timezone_type] => 3
[timezone] => America/New_York
)
[state] => OH
)
)
I have json decode set to true for array output
$result = json_decode($response, true); // true turns it into an array
but when i try to echo the 'first_name' values it just returns empty.
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
Yet i can return an indexed value
echo 'First Name: ' . $result[0]['first_name'] . '<br />';
What am i doing wrong here?
Your result array is nested 2 deep. $result is an array of arrays. So:
$result[0]['first_name']
or
foreach ($result as $r) {
echo $r['first_name'];
}
Response depend on server answer your request, the following work perfect to extract access token for example, you can try the following steps to test what you have and extract what you need too
After
$response = curl_exec($ch);
curl_close($ch);
I start to show what I get by
Test:
print_r ($response);
Then go to extract (where server response ) header and body to use what available in each of them
list($header, $body) = explode("\r\n\r\n", $response, 2);
Test:
echo $header;
echo $body;
then I’m extract item in $body to use in my code using stdClass
$bodyObject = json_decode($body);
Test:
print_r($bodyObject);
Test:
echo $bodyObject->access_token;
Related
I'm using a cURL request to grab data from a website and adding them to properties within a loop later. However, I'm stuck on making the data adjustable enough where I can add them directly within the objects.
I have a cURL request that I'm calling that grabbing all the content that I need as below:
public function request()
{
$resource = curl_init();
curl_setopt(
$resource,
CURLOPT_URL,
'lorem ipsum'
);
curl_setopt(
$resource,
CURLOPT_HTTPHEADER,
['API Auth']
);
curl_setopt(
$resource,
CURLOPT_REFERER,
'http://' . $_SERVER['SERVER_NAME'] . '/'
);
curl_setopt(
$resource,
CURLOPT_USERAGENT,
'F'
);
curl_setopt(
$resource,
CURLOPT_RETURNTRANSFER,
1
);
$response = json_decode(curl_exec($resource), true);
if (!curl_errno($resource)) {
$info = curl_getinfo($resource);
echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
};
return $response;
}
When I call the following execution $offices_array = $this->request(); print_r2($offices_array);, this is the return that I receive:
Array
(
[paginator] => Array
(
[total] => 131
[per_page] => 500
[current_page] => 1
[last_page] => 1
[prev_page] =>
[next_page] =>
)
[data] => Array
(
[0] => Array
(
[id] => 1
[name] => Atlanta
)
I'm using this function _csv_to_array:
private function _csv_to_array($filepath) {
$data_array = array();
if(is_readable($filepath)) {
$fp = fopen($filepath, 'r');
while(($data_item = fgetcsv($fp, 1000, "\t")) !== false) {
$data_array[] = array_map('utf8_encode', $data_item);
}
fclose($fp);
}
return $data_array;
}
to print out data as this:
Array
(
[0] => Array
(
[0] => ABU DHABI
[1] => FHI
)
How could I do something similar with the cURL request?
I need to interpret the array received from a remote licensing.
I am calling the remote api via curl and the answer in the browser is:
The parsed answer from curl done by using:
parse_str(curl_exec($ch), $parsed);
print_r($parsed);
is exactly as here:
Array ( [{"success":true,"uses":154,"purchase":{"id":"GYFt6sW7hbURSVdSpipb5g] => =","created_at":"2015-06-06T16:44:41Z","email":"askolon11#gmail.com","full_name":"daniel","variants":"","custom_fields":[],"product_name":"Direkt 1.2","subscription_cancelled_at":null,"subscription_failed_at":null}} )
I tried already for several hours to get the "success" item so later on to check it if it is true or false.
I used
while (list($var, $val) = each($parsed)) {
print "$var is $val\n";
}
but the result is the same.
Also I tried:
$parsed[0]['success'] or $parsed[0]['success']
and no result as well.
My full code is:
<?php $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.gumroad.com/v2/licenses/verify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array( 'product_permalink' => 'skQsA', 'license_key' => 'AB26AD9D-1B3B42E0-92356540-CF4E7C1B' );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$output = array();
parse_str(curl_exec($ch), $parsed);
print_r($parsed); // HERE WE HAVE THE ARRAY
while (list($var, $val) = each($parsed)) {
// print "$var is $val\n";
}
curl_close($ch);
?>
Thank you.
The API seems to return a JSON encoded string. So instead of:
parse_str(curl_exec($ch), $parsed);
use:
$parsed = json_decode(curl_exec($ch), true);
Then a print_r($parsed) will output:
Array
(
[success] => 1
[uses] => 154
...
)
And for checking success value:
if ($parsed['success']) {
// Do stuff
}
Instead of doing
$parsed[0]['success'];
try just
$parsed['success'];
If the array you are getting back is an associative array, then the 'key' will be the word 'success'.
$parsed = [
"success" => true,
"uses" => 154,
"purchase" =>
[
"id" => "GYFt6sW7hbURSVdSpipb5g] => =",
"created_at" => "2015-06-06T16:44:41Z",
"email" => "askolon11#gmail.com",
"full_name" => "daniel",
"variants" => "",
"custom_fields" => [],
"product_name" => "Direkt 1.2",
"subscription_cancelled_at" => null,
"subscription_failed_at" => null
]];
if($parsed['success'])
echo 'true';
else
echo 'false';
Below is my code, I am trying to get particular api response (msg,amt) in php string.
........................................................................................................................................
$key = "XXXXX";
$mykey = "XXXXX";
$command = "Check";
$value = "5454355435";
$r = array('key' => $key , 'value' => $value, 'command' => $command);
$qs= http_build_query($r);
$wsUrl = "https://info.service-provider.com";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $wsUrl);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $qs);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
$o = curl_exec($c);
if (curl_errno($c)) {
$sad = curl_error($c);
throw new Exception($sad);
}
curl_close($c);
$valueSerialized = #unserialize($o);
if($o === 'b:0;' || $valueSerialized !== false) {
print_r($valueSerialized);
}
print_r($o);
RESPONSE:
{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}
Your string is in json format. To get value from it, you should convert it into an array like this:
$json = '{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}';
$array = json_decode($json, true);
echo '<pre>'; print_r($array);
Your array will look like this:
Array
(
[status] => 1
[msg] => 1 out of 1 Transactions Fetched Successfully
[transaction_details] => Array
(
[2767712494] => Array
(
[mihpayid] => 268999084
[request_id] =>
[ref_num] => 020814301298
[amt] => 1.00
[txnid] => 5454355435
[additional_charges] => 0.00
[productinfo] => SHIRT
)
)
)
To get msg you should write like this:
echo $array['msg'];
You can get more information from json_decode
Let me know for more help.
This response looks like JSON format.
Pass this response string to php method json_decode like:
$response = json_decode($yourResponseString,true);
and then you should be able to access it's properties like a regular associative array:
$msg = $response['msg'];
I'm working on a project and trying to find a way to add my api results to mysql.
Here is the page were you can find the results.
Here is the code of the page:
<?php
///PLOT PROJECT USER REQUEST
//HELPER FUNCTION TO PRINT TO CONSOLE
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
//PLOT PROJECT REQUEST
$appId = '9fed0c75ca624e86a411b48ab27b3d5a';
$private_token = 'VGjPehPNBa5henSa';
$qry_str = "/api/v1/account/";
$ch = curl_init();
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode($appId.":".$private_token) // <---
);
$geofenceId = '736cb24a1dae442e943f2edcf353ccc7';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, 'https://admin.plotprojects.com/api/v1/notification/?geofenceId=' . $geofenceId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
?>
You can use json_decode() to decode your JSON string and take the values that you need to make your query. Read more at:
http://php.net/manual/en/function.json-decode.php
<?php
//The response from http://www.jobsinsac.com/api/api_notification.php
$json = '{ "success": true, "result": { "data": [{ "placeId": "736cb24a1dae442e943f2edcf353ccc7", "cooldownDays": 0, "triggerTimes": "inherit", "state": "published", "cooldownSeconds": 1, "data": "http://www.illuminatimc.com", "enabled": true, "geofenceId": "736cb24a1dae442e943f2edcf353ccc7", "id": "0cad6b54d225459e85cd8c27567f8b0b", "message": "Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.", "created": "2015-03-17T18:54:41Z", "timespans": [], "handlerType": "landingPage", "trigger": "enter" }], "total": 1 } }';
$data = json_decode($json, true);
print_r($data);
?>
Output:
Array
(
[success] => 1
[result] => Array
(
[data] => Array
(
[0] => Array
(
[placeId] => 736cb24a1dae442e943f2edcf353ccc7
[cooldownDays] => 0
[triggerTimes] => inherit
[state] => published
[cooldownSeconds] => 1
[data] => http://www.illuminatimc.com
[enabled] => 1
[geofenceId] => 736cb24a1dae442e943f2edcf353ccc7
[id] => 0cad6b54d225459e85cd8c27567f8b0b
[message] => Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.
[created] => 2015-03-17T18:54:41Z
[timespans] => Array
(
)
[handlerType] => landingPage
[trigger] => enter
)
)
[total] => 1
)
)
I am trying to import Google contacts in my code. I've successfully imported the contacts but my problem is that, I have to create an array of imported email addresses and I need to pass it to another page. But when I try to create an array, I get an array containing SimpleXMLElement Object.
Here is my code:
oauth.php:
<?php
$client_id='my-cient-id';
$client_secret='my-client-secret';
$redirect_uri='my-redirect-uri';
$max_results = 100;
$auth_code = $_GET["code"];
function curl_file_get_contents($url)
{
$curl = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,FALSE);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&oauth_token='.$accesstoken;
$xmlresponse = curl_file_get_contents($url);
if((strlen(stristr($xmlresponse,'Authorization required'))>0) && (strlen(stristr($xmlresponse,'Error '))>0)) //At times you get Authorization error from Google.
{
echo "<h2>OOPS !! Something went wrong. Please try reloading the page.</h2>";
exit();
}
echo "<h3>Email Addresses:</h3>";
$xml = new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');
foreach ($result as $title) {
$var=$title->attributes()->address;
echo $var . "<br>"; //here imported contacts is listing properly
$gc[]=array($var); // creates my contacts array
}
print_r($gc); //printing the created array
?>
My result is:
Array ( [0] => Array ( [0] => SimpleXMLElement Object ( [0] => email-address1 ) ) [1] => Array ( [0] => SimpleXMLElement Object ( [0] => email-address2 ) ) )
I need to get like this:
Array ( ([0] => email-address1 ) ( [1] => email-address2 ) )
Can anyone suggest me how to do this. I'm stuck in this for many days. Thanks in advance
Edit
XML Response:
Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [rel] => http://schemas.google.com/g/2005#other [address] => emailaddress1 [primary] => true ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [rel] => http://schemas.google.com/g/2005#other [address] => emailaddress2 [primary] => true ) ) )
I have to separate the emailaddress from the response to a php array.!
Edit 2
here is $xmlresponse:
email-id 2015-01-07T09:03:23.311Z profile-name email-id Contacts 2 1 100 http://www.google.com/m8/feeds/contacts/email-id/base/6cc9fe478fd427bb 2014-12-30T04:54:29.902Z
email-id is the mail id from which contacts are imported.
In the first line of the final foreach loop you could try:
$var=(string)$title->attributes()->address;
or:
$var=(string)$title->attributes()->address[0];
Which is a bit of code from http://php.net/manual/en/simplexml.examples-basic.php#116435
I think that the echo statement that lists the email addresses properly is implicitly calling the SimpleXMLElement::_toString(void) method (http://php.net/manual/en/simplexmlelement.tostring.php). So to get the same result when creating the array you can coerce it to a string by putting (string) in front of the variable name.
EDIT:
You might also try this where you add to the array:
$gc[] = $var;
instead of
$gc[] = array($var);
Since the second way creates a new array object and adds $var to it then the assignment operator adds that entire array to $gc. Which would explain why the SimpleXMLObject was itself in an array. The first way ('$gc[] = $var;') will add a new element to the array $gc. Or you could initialise $gc before the foreach loop with:
$gc = array();
And then inside the foreach loop use:
array_push($gc, $var);
You will need to do both of the suggested changes to get the result you want, so:
foreach ($results as $title) {
$var=(string)$title->attributes()->address;
$gc[] = $var;