2011-10-05 134 views
0

我已经学会了很多XML处理,但是我很喜欢JSON,想知道如何去用PHP(或jQuery)来解析下面的数据。 如果我如何处理JSON返回数组?

$var = file_get_contents("http://wthashtag.com/api/v2/trends/active.json"); 

(这就是趋势的数据的Twitter的JSON回报) 然后,

$obj = var_dump(json_decode($var)); 

的URL是在JSON url变量,胡说是名称的变量和文本在这里,指的是文字:变量的JSON 我将如何采取http://wthashtag.com/api/v2/trends/active.json输入JSON,并将其输出为:

<a href="http://twitter.com/search?q=blah">Blah</a><br>(text here)

这真的让我感到困惑:S我在SO和Google以及PHP手册上尝试了一些其他的反应,没有获得成功的结果,我能得到的最好的结果是echo'ing $ obj作为json解码的字符串随处都有一个对象(stdclass)数组。

回答

0

这是你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 />'; 
} 
?> 
+0

非常感谢! Foreach是要走的路,嗯..谢谢:) – Karan

+0

如果请求失败,解码失败,数组成员仍为空,则仍然需要添加错误处理 –

0

使用json_decode时,您正在创建一个数组。请在json_decode($var)一个print_r,你会得到多维数组结构 - 那么你就可以这样做:

echo $jsonArray['something']['text']; 
1

您可以json_decode()返回一个对象或数组(通过设置第二个参数为true)。之后,您可以使用该对象/数组中的值(在您的案例中为$obj)进行进一步处理。例如:

foreach ($obj->trends as $trend) { 
    echo '<a href="' . $trend['url'] . '">' . $trend['name'] . '</a>'; 
} 
0

这里后收到一个对象,你去

<?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>"; 
} 

?>