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条)

报告相同问题?