开发者

Print out JSON with PHP

Nothing shows on the screen, is this valid code below? I know theres a JSON parameter called 'text' within the received data but not sure how to print it out?

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


This should work:

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

It's a good idea to try something like var_dump($obj) when you run into an issue like this. After doing so, it becomes immediately clear $obj[0]->text is what you're after.

@benhowdle89 comment:

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


You should assign the value returned by get_data to a variable and pass it to json_decode i.e.:

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


$data is not set, and you don't need the curly braces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜