【问题标题】:How to get all XML elements in PHP (including supplementary information inside tags)如何在 PHP 中获取所有 XML 元素(包括标签内的补充信息)
【发布时间】:2012-07-10 12:49:11
【问题描述】:

我有以下从外部站点获取的 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

【问题讨论】:

  • 我试过simplexml_load_file,但不知道如何获得id

标签: php xml xml-parsing


【解决方案1】:

这个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";
}

【讨论】:

  • 顺便说一句,php 文档没有给出有关如何使用 simplexml 的正确示例。感谢您提出这个问题!
【解决方案2】:

您可以使用SimpleXMLxpath()

【讨论】:

    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 2018-12-06
      • 2020-02-01
      相关资源
      最近更新 更多