SimpleXML 解析具有相同名称和属性的子项
SimpleXML Parse Children With Same Name and Attributes
我不知道如何使用 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"];
我不知道如何使用 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"];