用 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
Print out JSON with PHP
提问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]->text
is 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
$data
is not set, and you don't need the curly braces.
$data
未设置,并且您不需要花括号。