question about php decode JSON
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->Docmu开发者_开发百科ltimedia->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
精彩评论