我希望 JSON 数据在 php 中考虑 foreach 循环,但每次我尝试这样做时都会收到此错误消息:
可捕获的致命错误:无法转换类 stdClass 的对象 串起来
PHP:
<?php
$xml_events = simplexml_load_file('xml_data/current_events.xml');
$results = array();
foreach ($xml_events->event as $event) {
array_push($results, array(
'name' => $event->name,
'cover' => $event->cover,
));
}
$data = json_encode($results);
$json = json_decode($data);
foreach ($json as $name)
{
echo $name->name;
}
XML:
<?xml version="1.0"?>
<data>
<event>
<name>Barclays ATP World Tour Finals</name>
</event>
</data>
JSON 数据:
"[{"name":{"0":"Barclays ATP World Tour Finals"}},{"name":{"0":"2015 National Television Awards"}},{"name":{"0":"Barclays ATP World Tour Finals"}},{"name":{"0":"Barclays ATP World Tour Finals"}},{"name":{"0":"Barclays ATP World Tour Finals"}},{"name":{"0":"Doctor who"}},{"name":{"0":"Apple Party"}},{"name":{"0":"ice-cream"}}]"
$name 是一个对象,所以解决方案是使用:
echo $name->name->{0};