如何在PHP中获取所有XML元素(包括标签内的补充信息)

时间:2012-07-10 12:49:12

标签: php xml xml-parsing

我从外部网站获取以下XML代码:

<source>
  <url>http://externalsite.com</url>
  <widget id="1">
    <title>Title1</title>
  </widget>
  <widget id="2">
    <title>Title2</title>
  </widget>
  <widget id="3">
    <title>Title3</title>
  </widget>
  <widget id="4">
    <title>Title4</title>
  </widget>
  <widget id="5">
    <title>Title5</title>
  </widget>
</source>

如何获取PHP中每个小部件的idtitle

3 个答案:

答案 0 :(得分:3)

worked for me

$xml = simplexml_load_string( $xml);
foreach( $xml->xpath( '//widget') as $el) {
    $attributes = $el->attributes();
    $children = $el->children(); // OR: $el->xpath('title'); if children vary
    echo $attributes['id'] . ' ' . $children[0] . "\n";
}

答案 1 :(得分:1)

您可以使用SimpleXMLxpath()

答案 2 :(得分:0)