How to Handle JSON Return Array?
I've learnt quite a bit of XML handling, but I'm crap with JSON, and wondering how I would go about parsing the following data with PHP (or jquery). If I were to
$var = file_get_contents("htt开发者_开发问答p://wthashtag.com/api/v2/trends/active.json");
(That's a Twitter JSON return of trends data) then,
$obj = var_dump(json_decode($var));
The URL being the url variable in the json, Blah being the name variables, and text here, referring to the text: variable in the json How would I take the input json of http://wthashtag.com/api/v2/trends/active.json, and output it as:
<a href="http://twitter.com/search?q=blah">Blah</a><br>(text here)
It's really confusing to me :S I've tried some other responses on SO and Google as well as the PHP manual, none yield successful results, the best I could get was echo'ing $obj as a json-decoded string with an object(stdclass) array everywhere.
You can make json_decode()
return an object or an array (by setting the second parameter to true
). After that, you can use the values in that object/array (in $obj
in your case) for further processing. Example:
foreach ( $obj->trends as $trend ) {
echo '<a href="' . $trend['url'] . '">' . $trend['name'] . '</a>';
}
This is a object that you receive after json_decode
<?php
$object = json_decode(file_get_contents("http://wthashtag.com/api/v2/trends/active.json"));
foreach($object->trends as $trend){
echo '<a href="'.$trend->url.'">'.$trend->name.'</a><br />'.$trend->description->text.'<br />';
}
?>
When using json_decode
you're creating an array. Do a print_r
on the json_decode($var)
and you'll get the multi-dimensional array structure - you'll then be able to do something like:
echo $jsonArray['something']['text'];
Here you go
<?php
$var = file_get_contents("http://wthashtag.com/api/v2/trends/active.json");
$json = json_decode($var);
foreach($json->trends as $lol){
echo "<a href=".$lol->url.">".$lol->name."</a><br>";
}
?>
精彩评论