I still have some question about php decode JSON.
the JSON return like this.
all({"Total":30,"Debug":null,"Documents":[
{
"DocTitle":"Image: A municipal police officer takes positio",
"Docmultimedia":[
{
"DocExpire":"2/7/2011 1:39:02 PM"
}
]
}
...]
});
this is my php code:
foreach ($data->Documents as $result) {
echo htmlspecialchars($result->DocTitle).'<br />';
if(!empty($result->Docmultimedia)){
echo htmlspecialchars($result->Docmultimedia->DocExpire).'<br />';
}
}
It return Warning: Invalid argument supplied for foreach().
and echo htmlspecialchars($result->Docmultimedia->DocExpire), is it write right? Thanks all.
Precondition:
The question is based on an MSNBC api (http://api.msnbc.msn.com/documents/GetDocuments?keyword=usa&jsonp=all)
Answer:
API Call
You should call the API without the trailing &jsonp=all, this will make the json evaluateable
API Result
MSN returns some values with NaN, NaN is no valid JSON as JSONLint proved.
Result Digesting
I provide a working example on GIST for digesting.
Docmultimedia is an array, as indicated by "Docmultimedia": [ { ... } ]
you have to call $result->Docmultimedia[0]->DocExpire to retrieve it. alternatively iterate over it.
I noticed that in the APIs result no Docmultimedia occurs ever, instead DocExpire is an property of the document. Retrieve it via $result->DocExpire.
First, what you are receiving is JSONP, not pure JSON. In order to decode the JSON, you have to remove, all(...); first:
$data = trim($json, 'all();');
Second, you need to decode JSON. PHP does not do this automatically:
$data = json_decode($data);
Now you should be abel to do:
foreach($data->Documents as $result) {
// something
}
DEMO
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
Here's the json
{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}
Here's my code
$json = json_decode($data);
foreach($json["result"] as $result){
foreach($result["files"] as $file){
echo $file["file_code"];
}
}
I want to extract all values from the "file_code". I got an error
Warning: Invalid argument supplied for foreach()
I was able get the VALUE of the first one using
echo $json->result->files[0]->file_code;
Is it possible to use a LOOP for the files[0]?
This line:
foreach($json["result"] as $result){
sees $json['result'] as an object, and so the next line tests for total_pages["files"], which doesn't exist.
Putting both foreach's together solves the problem:
$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}';
$json = json_decode($data, true);
foreach($json["result"]["files"] as $file)
print $file["file_code"];
Teh playground
Alternatively, make the JSON result into an array, and use object property accessors instead of associative array bindings.
$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":[{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}]}';
$json = json_decode($data);
foreach($json->result as $result){
foreach($result->files as $file){
echo $file->file_code;
}
}
Teh playground
I replicated your situation and it turns out that your JSON is invalid. You're missing a } at the end.
The reason for not getting an exception is because json_decode does not throw an error by default. You can make it do so by adding the JSON_THROW_ON_ERROR flag,
read the docs for more info.
This works perfect for me. If you have any thoughts please feel free to correct me.
$num = count($json->result->files);
echo $num;
for($i=0;$i<$num;$i++)
{
echo $json->result->files[$i]->file_code;
}
Hello I've been trying to solve this by myself for a few hours now, with zero luck. I'm trying to use the foreach command in php to display a decoded value from json.
{
-car_data: {
car_id: "87",
car_cost: "62000",
So let's say I want to display the value of car_id, then below that the value of car_cost.
I need to do this using the foreach command. Please briefly explain the process. I'd greatly appreciate it!
It's not clear exactly what you're asking...
If you have a JSON object and need to do something with it server side it is completely different to if you have a JSON object and want to do something with it on the webpage.
N.B.
Your JSON object is malformed there shouldn't be a - in the names.
JSON Object
Made on the client side will look something like:
var cars = {car_data: {car_id: 87, car_cost: 62000}};
Alternatively, server side, you need to convert it to a PHP readable format:
$cars = json_decode('{"car_data":{"car_id":87,"car_cost":62000}}');
JavaScript - Client Side
for(key in cars.car_data){
console.log(key + " => " + cars.car_data[key]);
}
PHP - Server Side
foreach($cars->car_data as $key => $value){
echo "{$key} => {$value}\n";
}
$decoded = json_decode($json);
foreach($decoded->cars_data as $car){
echo $car->car_cost;
}
<?php
$json_string = file_get_contents('infile.json');
fwrite($fileout, $json_string);
var_dump(json_decode($json_string));
$get_json_values=json_decode($json_string,true);
if(is_array($get_json_values))
{
foreach ($get_json_values as $getlikes) { ?>
<li>
<a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
</li>
<?php
} }
?>
I am trying to get values from a json file and I just can't figure out why var_dump returns NULL. Also, if I remove the if, for obvious reasons, there is a
Warning: Invalid argument supplied for foreach()
Please help me with this, i've been working on this the whole day and it's just so frustrating that it doesn't work out in any way.
Note: The name of the file is correct, the file is in the same directory with the .php file, there is data in infile.json and it is printed when fwrite($fileout, $json_string); is done.
What would be the problem, and what should I do?
Edit: The json file has about 1000 entries containing facebook page data. They all have the following structure:
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762","created_time":"2013-03-09T23:00:54+0000"}
var_dump($json_string) prints the data from the file.
if this helps in any way, the json file can be downloaded here
I have made up my json like this:
function idx(array $array, $key, $default = null) {
return array_key_exists($key, $array) ? $array[$key] : $default;
}
$likes = idx($facebook->api('/me/likes'), 'data', array());
foreach ($likes as $like) {
fwrite($fileout,json_encode($like));
fwrite($fileout,PHP_EOL );
?>`
So, what should I change would be:
1) add fwrite($fileout, "["); before and fwrite($fileout,"]"); after foreach.
2) add fwrite($fileout,",") before fwrite($fileout,PHP_EOL );
Is this right?
Your JSON file IS invalid.
Basically you have plenty of lines that are all valid JSON in itself, but they are not valid combined!
Invalid:
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762","created_time":"2013-03-09T23:00:54+0000"}
{"category":"Travel\/leisure","name":"Me hitchhiking around the world","id":"221159531328223","created_time":"2013-03-09T13:24:06+0000"}
Would be valid:
[
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762","created_time":"2013-03-09T23:00:54+0000"}
,
{"category":"Travel\/leisure","name":"Me hitchhiking around the world","id":"221159531328223","created_time":"2013-03-09T13:24:06+0000"}
]
You can either decode the JSON line by line, or convert it into a valid format.
You likely have invalid JSON in infile.json. Per the docs of json_decode():
NULL is returned if the json cannot be decoded or if the encoded data is deeper
than the recursion limit.
I am trying to JSON encode the results of my SQL SELECT statement using PHP and am unsure if I am formatting my array correctly before encoding.
My PHP code is:
$stmt = $this->db->prepare('SELECT CLINIC.clinic_name AS "clinicname" FROM CLINIC ORDER BY CLINIC.clinic_name ASC');
$stmt->execute();
$stmt->bind_result($clinicname);
$test = array();
while($stmt->fetch()){
$tempArray = array('clinicname' => $clinicname);
array_push($test, $tempArray);
}
$stmt->close();
// Return clinics, encoded with JSON
header('Content-type: application/json');
$json = json_encode($test);
echo $json;
The result of this array creation and encoding is:
[{"clinicname":"Bangor"},{"clinicname":"Belfast"},{"clinicname":"Crumlin"},{"clinicname":"Londonderry"}]
So I have an array of arrays.
Will this be okay for sending as JSON? All the examples I see seem to be a single array. Am I correct so far?
And then, regarding iOS, will the received object be a NSDictionary or an NSArray?
Any help or feedback on the above would be greatly received.
Matt.
Yes, your JSON is properly formatted. Next time you can use a JSON validator to check.
Also, some details on json_encoding.
A [] represents an array and {} represents an object.
In iOS, if this is the result from an http request, it will be of type NSString, and then need to be parsed by something like:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
which then converts it to NSArray, NSDictionary NSString, etc.
Yes, you can send an array of arrays, and you can acces like the follow way:
$response = json_decode($response,true);
foreach ($response as $resp)
{
echo "<br>";
print_r($resp);
}
json example:
[{"id":"38","first_name":"prueba","second_name":"example","first_surname":"prueba","second_surname":"GONZALEZ","email":"x#x.net","network_login":"x.x","pos_name":"x x","position":"1","active":"1"},{"vhur":"292","first_name":"c","second_name":"example","first_surname":"example","second_surname":null,"email":"example#example.com","network_login":"example.example","pos_name":"example example","position":"2","active":"1"}]
I have the json object from remote site. When I vardump the json response. The output looks like this..
object(GSResponse)#111 (7) {
["errorCode":"GSResponse":private]=>
int(0)
["errorMessage":"GSResponse":private]=>
NULL
["rawData":"GSResponse":private]=>
string(1808) "{
"UID": "*********",
}
]
}
How can I access the rawData parameter in the json response using php. Is there any function to convert it into php array.
I appreciate any help.
Edited - updated to include the comments
Answer
Lets say that $gsresponsevar is an object of type gsresponse, as defined below.
decode the json response-
$myjsonresponse= json_decode($gsresponsevar->getResponseText()) ;
Alternatively retrieve the var
echo $gsresponsevar->getString('uid');
Documentation
Extract from: http://developers.gigya.com/030_Server_SDKs/PHP/Reference/Class_GSResponse
string getString(string $key [, string $defaultValue])
this is the generic "frameworkless" native way
you can use JSON_decode to decode a JSON-string
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$dataObject = json_decode($json);
$dataArray = json_decode($json, true);
The second parameter defines whether you get an object (accessible via $dataObject->key) or an associative array (accessible via $dataArray['key']).
Be aware of the common mistakes mentioned in the API "Example #3 common mistakes using json_decode()"
This is the Gigya-API usage way
See the answer from Jason for more details for this
$responseObject->getString('key');
you can use json_decode($json_array);
for print your resulted array you can write var_dump(json_decode($json_array));
Thankx.