用 PHP 打印 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4696094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:00:04  来源:igfitidea点击:

Print out JSON with PHP

phpjson

提问by benhowdle89

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?

屏幕上什么都没有显示,这是下面的有效代码吗?我知道接收到的数据中有一个名为“text”的 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;
    }
    ?>

回答by mfonda

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]->textis what you're after.

var_dump($obj)当您遇到这样的问题时,尝试类似的方法是个好主意。这样做后,您会立即清楚$obj[0]->text您的目标是什么。

@benhowdle89 comment:

@benhowdle89 评论:

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

回答by Chandu

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

您应该将 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;
    }
    ?>

回答by profitphp

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

$data未设置,并且您不需要花括号。