PHP get value from an array - php

I have this PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch))
die("Connection Error: ".curl_errno($ch).' - '.curl_error($ch));
curl_close($ch);
$arr = json_decode($jsondata);
echo "\nResponse: ".htmlentities($jsondata)."\n\nArray: ".print_r($arr,true);
Which outputs:
Response: {"result":"success","clientid":83} Array:
stdClass Object ( [result] => success [clientid] => 83 )
I want to grab the value 83 stored in the variable called $clientid.
But I can't figure out how to do it.

You are confusing a PHP object with a PHP array.
You should be doing this: echo $arr->clientid;
Example 1, access a value of an object like this:
<?php
$jsondata = '{"firstName":"John", "lastName":"Doe"}';
$arr = json_decode($jsondata);
echo gettype($arr);
echo $arr->firstName;
?>
This prints:
object
John
Example 2, access a value of an array like this:
<?php
$yarr = array(5,6,7);
echo $yarr[0];
?>
This prints:
5

Your main mistake is assuming json_decode returns an array.
$arr = json_decode($jsondata);
Will set up $arr as an object. If you wanted to access it as an array, you can do this:
$arr = json_decode($jsondata, TRUE);
The extra parameter on the end tells json_decode to return an array instead of an object. Then you could do:
echo $arr["clientid"];

try echo $arr["clientid"] to get data from array

Related

How can I convert my API response into PHP Array?

I Have this data from my API Call.
[{\"packagename\":\"Book+-+Outliers\",\"trackingnumber\":\"1Z2FF4063A00030059\",\"packageweight\":\"1.0000\",\"weightunit\":\"Lbs\",\"price\":\"16.9900\",\"suiteno\":[],\"user_id\":\"NOTFOUND\"},{\"packagename\":\"Book+-+Outliers\",\"trackingnumber\":\"1Z2FF4063A00030059\",\"packageweight\":\"1.0000\",\"weightunit\":\"Lbs\",\"price\":\"16.9900\",\"suiteno\":\"TY1000234\",\"user_id\":\"1000234\"},{\"packagename\":\"Book+-+David+%26+Goliath+%3B+Face+Cream+-+Clinique%2FGlycolix\",\"trackingnumber\":\"9.36E+21\",\"packageweight\":\"2.0000\",\"weightunit\":\"Lbs\",\"price\":\"18.0000\",\"suiteno\":\"TY1000234\",\"user_id\":\"1000234\"},{\"packagename\":\"Sunglasses+-+Valentino\",\"trackingnumber\":\"1.02E+33\",\"packageweight\":\"0.5000\",\"weightunit\":\"Lbs\",\"price\":null,\"suiteno\":\"TY1000431\",\"user_id\":\"1000431\"},{\"packagename\":\"Sunglasses+-+Safilo+group\",\"trackingnumber\":\"1.01E+33\",\"packageweight\":\"0.8000\",\"weightunit\":\"Lbs\",\"price\":null,\"suiteno\":\"TY1000431\",\"user_id\":\"1000431\"},{\"packagename\":\"Pigmentation+Color+Tobacco\",\"trackingnumber\":\"'42060106''9405510200830072094975'\",\"packageweight\":\"0.6300\",\"weightunit\":\"Lbs\",\"price\":\"320.0000\",\"suiteno\":[],\"user_id\":\"NOTFOUND\"}]
How can I convert this data into PHP Array? I tried using json_decode($result,true) but it is not working properly. Thanks in advance.
UPDATE:
My PHP Code
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode(stripslashes($result), true);
$json=str_replace("\\",'', $result);
$jsondata=json_decode($json,true);
print_r($jsondata);
//echo $result;
use json_decode() for this:
// It will convert the given json to an array
$arr = json_decode($json, true);
// The second param is for array, o/w it will return an object
Reference
$json='[{\"packagename\":\"Book+-+Outliers\",\"trackingnumber\":\"1Z2FF4063A00030059\",\"packageweight\":\"1.0000\",\"weightunit\":\"Lbs\",\"price\":\"16.9900\",\"suiteno\":[],\"user_id\":\"NOTFOUND\"},{\"packagename\":\"Book+-+Outliers\",\"trackingnumber\":\"1Z2FF4063A00030059\",\"packageweight\":\"1.0000\",\"weightunit\":\"Lbs\",\"price\":\"16.9900\",\"suiteno\":\"TY1000234\",\"user_id\":\"1000234\"},{\"packagename\":\"Book+-+David+%26+Goliath+%3B+Face+Cream+-+Clinique%2FGlycolix\",\"trackingnumber\":\"9.36E+21\",\"packageweight\":\"2.0000\",\"weightunit\":\"Lbs\",\"price\":\"18.0000\",\"suiteno\":\"TY1000234\",\"user_id\":\"1000234\"},{\"packagename\":\"Sunglasses+-+Valentino\",\"trackingnumber\":\"1.02E+33\",\"packageweight\":\"0.5000\",\"weightunit\":\"Lbs\",\"price\":null,\"suiteno\":\"TY1000431\",\"user_id\":\"1000431\"},{\"packagename\":\"Sunglasses+-+Safilo+group\",\"trackingnumber\":\"1.01E+33\",\"packageweight\":\"0.8000\",\"weightunit\":\"Lbs\",\"price\":null,\"suiteno\":\"TY1000431\",\"user_id\":\"1000431\"},{\"packagename\":\"Pigmentation+Color+Tobacco\",\"trackingnumber\":\"420601069405510200830072094975\",\"packageweight\":\"0.6300\",\"weightunit\":\"Lbs\",\"price\":\"320.0000\",\"suiteno\":[],\"user_id\":\"NOTFOUND\"}]';
$json=str_replace("\\",'', $json);
$jsondata=json_decode($json,true);
print_r($jsondata);
CURL output is json and in line $json_result = json_decode($result, true); you decoded it to an array, after str_replace you have an array but you decoded it again, may be if you remove $jsondata=json_decode($json,true); and return $json you receive an array
Your string \"trackingnumber\":\"'42060106''9405510200830072094975'\" has syntax error.
$result = '[{\"packagename\":\"Book+-+Outliers\",\"trackingnumber\":\"1Z2FF4063A00030059\",\"packageweight\":\"1.0000\",\"weightunit\":\"Lbs\",\"price\":\"16.9900\",\"suiteno\":[],\"user_id\":\"NOTFOUND\"},{\"packagename\":\"Book+-+Outliers\",\"trackingnumber\":\"1Z2FF4063A00030059\",\"packageweight\":\"1.0000\",\"weightunit\":\"Lbs\",\"price\":\"16.9900\",\"suiteno\":\"TY1000234\",\"user_id\":\"1000234\"},{\"packagename\":\"Book+-+David+%26+Goliath+%3B+Face+Cream+-+Clinique%2FGlycolix\",\"trackingnumber\":\"9.36E+21\",\"packageweight\":\"2.0000\",\"weightunit\":\"Lbs\",\"price\":\"18.0000\",\"suiteno\":\"TY1000234\",\"user_id\":\"1000234\"},{\"packagename\":\"Sunglasses+-+Valentino\",\"trackingnumber\":\"1.02E+33\",\"packageweight\":\"0.5000\",\"weightunit\":\"Lbs\",\"price\":null,\"suiteno\":\"TY1000431\",\"user_id\":\"1000431\"},{\"packagename\":\"Sunglasses+-+Safilo+group\",\"trackingnumber\":\"1.01E+33\",\"packageweight\":\"0.8000\",\"weightunit\":\"Lbs\",\"price\":null,\"suiteno\":\"TY1000431\",\"user_id\":\"1000431\"},{\"packagename\":\"Pigmentation+Color+Tobacco\",\"trackingnumber\":\"420601069405510200830072094975\",\"packageweight\":\"0.6300\",\"weightunit\":\"Lbs\",\"price\":\"320.0000\",\"suiteno\":[],\"user_id\":\"NOTFOUND\"}]';
$json_result = json_decode(stripslashes($result), true);
$json=str_replace("\\",'', $result);
$jsondata=json_decode($json,true);
print_r($jsondata);
Try this,
$jsonData = stripslashes(html_entity_decode($result));
$output = json_decode($jsonData, true);
echo "<pre>";
print_r($output);
echo "</pre>";
Or Try this way,
$out = preg_replace('/\\\"/',"\"", $result);
$output = json_decode($out, true);
echo "<pre>";
print_r($output);
echo "</pre>";

Parsing object in PHP not working

I'm using this to get my response (only relevant code below):
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$headr);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
$my_resp = $result['total_count'];
var_dump($my_resp);
echo $result gives me an object that appears to be valid JSON. Like this:
{
"total_count": 1
}
However, $my_resp comes back as NULL. What am I doing wrong here?
You need to turn it into an object from a string
$result = json_decode( curl_exec($ch));
or an associative array
$result = json_decode( curl_exec($ch), true );
If it is JSON, you should json_decode() it before trying to read fields.

How to merge cURL responses into one array?

I'm calling a function to get data from 3 different sources.
The $returnedData response is always an array. How to merge all 3 responses into one array?
function getData($xPostURL,$xToken,$xTokenSecret,$xAccount)
{
$datatopost = array (
"token" => $xToken,
"tokenSecret" => $xTokenSecret,
"account" => $xAccount,
);
$ch = curl_init ($xPostURL);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returnedData = curl_exec ($ch);
echo $returnedData;
}
getData("http://www.example.com/foo.php","","","");
getData("http://www.example.org/bar.php","","","");
getData("http://www.example.net/helloworld.php","","","");
Try use: array_merge
$a = getData("http://www.example.com/foo.php","","","");
$b = getData("http://www.example.org/bar.php","","","");
$c = getData("http://www.example.net/helloworld.php","","","");
$r = array_merge($a,$b,$c);
You can merge Arrays with this function http://php.net/manual/en/function.array-merge.php
If wel use this function your code will look something like this:
function getData($xPostURL,$xToken,$xTokenSecret,$xAccount)
{
$datatopost = array (
"token" => $xToken,
"tokenSecret" => $xTokenSecret,
"account" => $xAccount,
);
$ch = curl_init ($xPostURL);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returnedData = curl_exec ($ch);
return $returnedData;
}
$firstData = getData("http://www.example.com/foo.php","","","");
$secondData = getData("http://www.example.org/bar.php","","","");
$thirdData = getData("http://www.example.net/helloworld.php","","","");
$merged = array_merge($firstData, $secondData, $thirdData);
Now everything is in $merged
(Also did some indenting and changed echo $returnedData; to return $returnedData; echo only displays it, return returns it to the variable.

Getting json response in php

Does Php have a method that calls a Json URL, and save in a variable the data it fetches
for example can I used:
"https://www.googleapis.com/blogger/v3/blogs/1/posts/"
I been trying with this code, but i am not sure if this is wrking
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/1/posts/");
curl_setopt($ch, CURLOPT_HEADER, 0);
$df = curl_exec($ch);
curl_close($ch);
You can use the bulti-in function json_decode http://php.net/manual/it/function.json-decode.php
$json = file_get_contents("https://www.googleapis.com/blogger/v3/blogs/1/posts/");
$obj = json_decode($json); //returns an object of json values
$array = json_decode($json, true); //returns an array of json values
The problem is http*s*, try adding these:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

Get JSON object from URL

I have a URL that returns a JSON object like this:
{
"expires_in":5180976,
"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
}
I want to get JSON object from the URL and then the access_token value.
So how can I retrieve it through PHP?
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;
For this to work, file_get_contents requires that allow_url_fopen is enabled. This can be done at runtime by including:
ini_set("allow_url_fopen", 1);
You can also use curl to get the url. To use curl, you can use the example found here:
$ch = curl_init();
// IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $obj->access_token;
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Php also can use properties with dashes:
garex#ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
public $qwert-y =>
int(123)
}
=> null
You could use PHP's json_decode function:
$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];
You need to read about json_decode function http://php.net/manual/en/function.json-decode.php
Here you go
$json = '{"expires_in":5180976,"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"}';
//OR $json = file_get_contents('http://someurl.dev/...');
$obj = json_decode($json);
var_dump($obj-> access_token);
//OR
$arr = json_decode($json, true);
var_dump($arr['access_token']);
// Get the string from the URL
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452');
// Decode the JSON string into an object
$obj = json_decode($json);
// In the case of this input, do key and array lookups to get the values
var_dump($obj->results[0]->formatted_address);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $obj->access_token;
file_get_contents() is not fetching the data from url,then i tried curl and it's working fine.
Our solution, adding some validations to response so we are sure we have a well formed json object in $json variable
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
return false;
}
$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
return false;
}
my solution only works for the next cases:
if you are mistaking a multidimensaional array into a single one
$json = file_get_contents('url_json'); //get the json
$objhigher=json_decode($json); //converts to an object
$objlower = $objhigher[0]; // if the json response its multidimensional this lowers it
echo "<pre>"; //box for code
print_r($objlower); //prints the object with all key and values
echo $objlower->access_token; //prints the variable
i know that the answer was has already been answered but for those who came here looking for something i hope this can help you
When you are using curl sometimes give you 403 (access forbidden)
Solved by adding this line to emulate browser.
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
Hope this help someone.
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'https://www.xxxSite/get_quote/ajaxGetQuoteJSON.jsp?symbol=IRCTC&series=EQ');
//Set the GET method by giving 0 value and for POST set as 1
//curl_setopt($curl_handle, CURLOPT_POST, 0);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$query = curl_exec($curl_handle);
$data = json_decode($query, true);
curl_close($curl_handle);
//print complete object, just echo the variable not work so you need to use print_r to show the result
echo print_r( $data);
//at first layer
echo $data["tradedDate"];
//Inside the second layer
echo $data["data"][0]["companyName"];
Some time you might get 405, set the method type correctly.

Categories