SimpleXML解析具有相同名称和属性的子项

时间:2015-08-17 22:02:45

标签: php xml simplexml

我无法弄清楚如何使用simpleXML解析这样的xml文件。

<root>
 <movies>
    <movie cast="some,actors" description="Nice Movie">Pacific Rim</movie>
    <movie cast="other,actors" description="Awesome Movie">Atlantic Rim</movie>
</movies>
</root>

我看到的预期输出类似于

Pacific Rim [cast="some,actors"],[description="Nice Movie"]
Atlantic Rim [cast="other,actors"],[description="Awesome Movie"]

我试过了

$xml=new SimpleXMLElement($xml_string);
foreach($xml->movies as $movie)
{
  echo $movie->cast." ".$movie->description;
}

感谢。

1 个答案:

答案 0 :(得分:2)

<?php
$xml_string = '<root>
 <movies>
    <movie cast="some,actors" description="Nice Movie">Pacific Rim</movie>
    <movie cast="other,actors" description="Awesome Movie">Atlantic Rim</movie>
</movies>
</root>';

/* Expected result: */

/* Pacific Rim [cast="some,actors"],[description="Nice Movie"] */
/* Atlantic Rim [cast="other,actors"],[description="Awesome Movie"] */

$xml = simplexml_load_string($xml_string);
foreach($xml->movies->movie as $movie)
{
    $name = (string) $movie;
    $attributes = $movie->attributes();
    print $name.' '.'[cast="'.$attributes['cast'].
          '"],[description="'.$attributes['description']."\"]\n";
}

此外,您可以使用此语法直接访问属性(无需调用attributes()):

print $movie["cast"] . " " . $movie["description"];