【问题标题】:SimpleXML Parse Children With Same Name and AttributesSimpleXML 解析具有相同名称和属性的子项
【发布时间】:2015-08-18 19:50:29
【问题描述】:

我不知道如何使用 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;
}

谢谢。

【问题讨论】:

  • 您是否尝试过重组您的 xml,使其不像 names

标签: php xml simplexml


【解决方案1】:
<?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"];

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2018-04-22
    • 2015-12-23
    相关资源
    最近更新 更多