2011-01-14 105 views
1

屏幕上没有显示,这个有效的代码在下面?我知道在接收到的数据中有一个名为'text'的JSON参数,但不知道如何将其打印出来?用PHP打印出JSON

<?php 
    $url='http://twitter.com/statuses/user_timeline/twostepmedia.json'; //rss link for the twitter timeline 
    //print_r(get_data($url)); //dumps the content, you can manipulate as you wish to 
    $obj = json_decode($data); 
    print $obj->{'text'}; 
    /* gets the data from a URL */ 

    function get_data($url) 
    { 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
    } 
    ?> 
+2

做`的print_r($ OBJ)`看到实际的结构。乍一看,整个json被包装在一个数组中,所以它可能是`$ obj [0] - > text`。 – mario 2011-01-14 21:27:07

+1

首先看看`$ obj`包含什么,然后从那里开始。 – 2011-01-14 21:27:38

回答

5

这应该工作:

$obj = json_decode(get_data($url)); 
$text = $obj[0]->text; 

这是一个好主意,当你遇到这样的问题,试图像var_dump($obj)。这样做后,立即清除$obj[0]->text就是你所追求的。

@ benhowdle89评论:

foreach ($obj as $item) { 
    $text = $item->text; 
} 
1

您应该指定由GET_DATA返回到一个变量的值,并将它传递到json_decode即:

<?php 
    $url='http://twitter.com/statuses/user_timeline/twostepmedia.json'; //rss link for the twitter timeline 
    //print_r(get_data($url)); //dumps the content, you can manipulate as you wish to 
    $data = get_data($url); 
    $obj = json_decode($data); 
    print $obj->text; 
    /* gets the data from a URL */ 

    function get_data($url) 
    { 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
    } 
    ?> 
0

$data没有设置,你不需要花括号。