我正在尝试从XML提要的属性中获取JSON提要输出。我可以从XML中获取数据,但是,我无法使其正确格式化。错误似乎在于json_encode
没有将大括号添加到输出的日期。这是我到目前为止的代码:
<?php
$url = 'http://cloud.tfl.gov.uk/TrackerNet/LineStatus';
if(!$xml = simplexml_load_file($url))
{
die("No xml for you");
}
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
echo $line->Line['Name'];
echo $line->Status['Description'];
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
?>
问题是您没有将名称和描述存储到数组中。
试试这个:
foreach ($xml->LineStatus as $line)
{
$linestatus[] = array('name' => $line->Line['Name']);
$linestatus[] = array('description' => $line->Line['Description']);
}
演示!
echo
把一切都搞砸了。 我认为您打算附加到linestatus
根据您的代码保持为空。
$linestatus[] = array(
"name" => $line->Line['Name'],
"description" => $line->Status['Description']
);
您还需要使用 echo
而不是 print_r
来实际发出 JSON。
您将$linestatus
声明为数组,然后在最终对其进行编码并尝试输出之前从未在其中放置任何内容。当然,它不会按预期工作!相反,您应该用值填充它:
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
$linestatus[] = $line->Line;
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));