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

标签 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;
}

谢谢。

最佳答案

<?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"];

关于php - SimpleXML 解析具有相同名称和属性的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060427/

相关文章:

PHP/MySQL : Simple timekeeping and update scheme?

php从对象插入mysql表

java - 如何扩展complexType但子类型中没有子元素?

php - SimpleXMLElement::addChild 似乎不适用于某些字符串

php - 有没有更快/更好的方法来代替在下面的代码中使用 preg_match?

php - 如何用PHP获取SVG标签内容

php - WP-查询 : check if the post content is empty

android - 如何自动弹出键盘?

android - 如何在Android中编辑XML并保存?

php - select语句在mysql上运行非常慢