来自孙子的XMLSimpleElement

时间:2014-05-20 13:55:38

标签: php xml-parsing

我正在尝试循环使用PHP中的以下xml字符串,但在使用xmlsimpleelement解析器时无法获取actor和ebook的childelements。

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:ff="some uri">
   <title>Fulfillments</title>
   <link rel="self" type="application/atom+xml" href="some uri" title="...." />
   <updated>2014-05-20T10:10:05Z</updated>

   <entry>
       <title>e90e7ea4e7ea4-8b6a-4355-a9e7-a448c8435126</title>
       <id>urn:uuid:e90e7ea4-8b6a-4355355-a9e7-a448c8435126</id>
       <updated>2014-05-20T10:10:05Z</updated>
       <summary>sometext</summary>
       <ff:created>2014-05-07T06:43:32Z</ff:created>
       <ff:modified>2014-05-07T06:43:32Z</ff:modified>
       <ff:price>50</ff:price>
       <ff:orderid>randomorderhash</ff:orderid>
       <ff:drmType>4</ff:drmType>
       <ff:actor>
           <ff:id>12345</ff:id>
           <ff:name>Actor Name</ff:name>
       </ff:actor>
       <ff:ebook>
           <ff:id>somerandomidhash</ff:id>
           <ff:ean>12345678</ff:ean>
           <ff:publisher>905555</ff:publisher>
           <ff:version>1</ff:version>
           <ff:drmType>4</ff:drmType>
           <ff:format>1</ff:format>
           <ff:size>750319</ff:size>
       </ff:ebook>
   </entry>

  <entry>
      ....

我的phpcode看起来像这样:

$data = simplexml_load_string($xmlstr);
$result = array();
foreach ( $data->children() as $entries ) {
    $item = array();
    foreach($entries->children() as $key => $entry) {
        $item[$key] = $entry;
    }

   foreach($entries->children('ff', true) as $key => $entry) {
        switch ($key) {
            case 'actor':
                // what do i write here to get the children?
            break;
            case 'ebook':
                // what do i write here to get the children?
            break;
            default:
                $item[$key] = $entry;
            break;
        }
    }
    $result[] = $item;
}

我尝试过使用children()和attributes(),但仍然很难获得actor和ebook的子元素。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

在这里工作:http://ideone.com/GfmqQh

foreach($entries->children('ff', true) as $key => $entry) {
    switch ($key) {
        case 'actor':
            // what do i write here to get the children?
            var_dump($entry->children('ff', true)->name);
            //if case you like get attributes... $entry->attributes(), return array of attributes
            echo "actor\n";
        break;
        case 'ebook':
            // what do i write here to get the children?
            echo "ebook\n";
        break;
        default:
            echo "$key default\n";
            $item[$key] = $entry;
        break;
    }
}
$result[] = $item;