doujia5863 2013-02-09 23:36
浏览 22
已采纳

SimpleXML load String将值放入PHP中的Array()中

I have a XML in form of String (after XLS transform):

<course>
    <topic>
        <chapter>Some value</chapter>
        <title>Some value</title>
        <content>Some value</content>
    </topic>
    <topic>
        <chapter>Some value</chapter>
        <title>Some value</title>
        <content>Some value</content>
    </topic>
    ....
</course>

Then I'm pushing above mentioned XML into the Array():

$new_xml = $proc->transformToXML($xml);

$xml2 = simplexml_load_string($new_xml);
$root = $xml2->xpath("//topic");

$current = 0;
$topics_list = array();

// put the xml values into multidimensional array
foreach($root as $data) {
    if ($data === 'chapter') {
        $topics_list[$current]['chapter'] = $data->chapter;
    }
    if ($data === 'title') {
        $topics_list[$current]['title'] = $data->title;
    }
    if ($data === 'content') {
        $topics_list[$current]['content'] = $data->content;
    }
    $current++;
}
print_r($topics_list);

Problem: Result is empty array. I've tried string like:

$topics_list[$current]['chapter'] = (string) $data->chapter;

but result is still empty. Can anyone explain, where is my mistake. Thanks.

  • 写回答

3条回答 默认 最新

  • dsvs50005 2013-02-10 20:04
    关注

    Because my topic element has only simple child elements and not attributes, I can cast it to array and add it to the list (Demo):

    $xml2 = SimpleXMLElement($new_xml);
    $topics_list = array();
    foreach ($xml2->children() as $data) {
        $topics_list[] = (array) $data;
    }
    

    The alternative method is to map get_object_vars on the topic elements (Demo):

    $topics_list = array_map('get_object_vars', iterator_to_array($xml2->topic, false));
    

    But that might become a bit hard to read/follow. Foreach is probably more appropriate.


    And here is the first working version of my code:

    $xml2 = SimpleXMLElement($new_xml);
    $current = 0;
    $topics_list = array();
    foreach($xml2->children() as $data) {
        $topics_list[$current]['chapter'] = (string) $data->chapter;
        $topics_list[$current]['title'] = (string) $data->title;
        $topics_list[$current]['content'] = (string) $data->content;
        $current++;
    }
    

    Thanks again to @Jack, @CoursesWeb and @fab for their investigation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器