如何通过php中的foreach循环传递JSON数据

时间:2015-01-26 20:33:08

标签: arrays xml json foreach

我希望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"}}]"

1 个答案:

答案 0 :(得分:0)

$ name是一个对象,因此解决方案是使用:

echo $name->name->{0};