我尝试使用以下代码在以下网址显示某些json数据中的某些元素,但它不显示任何内容。我有什么想法我做错了吗?
<?php
$url="http://fbclaurel.onthecity.org/plaza/events?format=json";
$data = file_get_contents($url);
$json = json_decode($data);
foreach($json->"global_event" as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
?>
答案 0 :(得分:3)
实际上,由于您配置的错误报告/显示设置,您可能会隐藏一个语法错误。它会是这样的
PHP Parse错误:语法错误,意外&#39;&#34; global_event&#34;&#39; (T_CONSTANT_ENCAPSED_STRING),期待标识符(T_STRING)或变量(T_VARIABLE)或&#39; {&#39;或者&#39; $&#39;
开发时,我建议您始终在php.ini
display_errors = On
error_reporting = E_ALL
我刚刚检查了该API中的数据并返回了一个数组。每个数组条目都是一个具有单个global_event
属性的对象,该属性本身就是另一个对象。我想你会需要这样的东西来迭代...
$json = json_decode($data, true);
// the second "true" argument forces an array format result.
// I find it more appropriate when iterate keys or when keys
// might be invalid property names.
foreach ($json as $obj) {
$globalEvent = $obj['global_event'];
// now $globalEvent is an array with keys such as
// addresses, body, created_at, ending_at, etc.
// Note that few of these properties are simple, scalar values (like strings),
// most are arrays themselves
// display example...
echo 'title: ', htmlspecialchars($globalEvent['title']), '<br>',
'short_url: ', htmlspecialchars($globalEvent['short_url']), '<br>';
}
答案 1 :(得分:0)
如下所示
$url="http://fbclaurel.onthecity.org/plaza/events?format=json";
$data = file_get_contents($url);
$json = json_decode($data);
//echo '<pre>';
//print_r( $json[0]->global_event);
array_walk_recursive($json[0]->global_event, function ($a,$b){
echo 'KEY :'.$b.' & Value :'.$a.'<br>';
});
<强> 输出 强>
KEY :starting_at & Value :2014-06-01T08:00:00-04:00
KEY :external_form_id & Value :
KEY :short_url & Value :http://bit.ly/1jOTqao
KEY :body & Value : Hymns are led by piano and organ. The choral music is sung by the Chapel Choir and the sermon message is given by Pastor Stan.
KEY :ending_at & Value :2014-06-01T09:00:00-04:00
KEY :euid & Value :9ea33765449eb1476530c84d44a01cf200709cf9
KEY :title & Value :Classic Worship Service
KEY :updated_at & Value :2014-05-25T22:28:24-04:00
KEY :created_at & Value :2014-05-25T22:28:23-04:00