2011-01-14 78 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沒有設置,你不需要花括號。