【问题标题】:Search for Values in XML [duplicate]在 XML 中搜索值 [重复]
【发布时间】:2014-06-10 01:38:26
【问题描述】:

我的 XML

<properties>
<property>
    <refno>001</refno>
    <status>active</status>
    <type>SP</type>
    <description>Text Text Text</description>
    <images>
      <image>Path_here</image>
      <image>Path_here</image>
      <image>Path_here</image>
    </images>
</property>
<property>
    <refno>002</refno>
    <status>active</status>
    <type>SP</type>
    <description>Text Text Text</description>
     <images>
      <image>Path_here</image>
      <image>Path_here</image>
      <image>Path_here</image>
    </images>
</property>
</properties>

我的 PHP 代码

if ($xml = simplexml_load_file($xml_file_here)) {
    foreach($xml->property as $i) {
        if ($i->refno == "1") {
            echo $i->description."<br />".
            echo $i->type;
        }
    }
}

我通常循环通过 XML 来查找 [refno] 值。有没有不需要循环的方法来搜索值?

【问题讨论】:

  • 您可以将此逻辑包装到一个函数中以返回匹配的元素,但这已经是正确的方法了。
  • 即使我正在循环数以千计的 节点?还有其他更好更快的方法吗?它使脚本执行缓慢。
  • 对您的 XML text 进行 if(strpos($your_xml_text, '&lt;refno&gt;12345&lt;/refno&gt;') !== false) { // do stuff } 调用以快速确定元素是否存在,然后如果它循环直到找到它呢?
  • 您只需要特定节点,还是需要节点及其完整层次结构?
  • 我需要得到匹配的 的兄弟姐妹(状态、类型、描述、图像)

标签: php xml


【解决方案1】:

您可以使用 XPath 表达式:

// find property element that contains a refno element with "001"
foreach ($xml->xpath('//property[contains(refno, "001")]') as $node) {
    echo (string)$node->description, "\n";
}

【讨论】:

  • 是唯一的,没有重复
  • @Ratbucoh 好吧,xpath() 返回一个找到的元素数组;随意选择第一个并跳过foreach。
  • @Ratbucoh 因为refno 是唯一的,只需将其分配给变量$values = $xml-&gt;xpath('//property[contains(refno, "001")]'); $values = reset($values);,您就可以自己获得值。这已经是正确答案了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
相关资源
最近更新 更多