在 PHP 中使用 XPaPath 不适用于 File


using xpath in php does not work with file

在 SimpleXMLElement 对象上应用xpath(),从字符串中加载 XML。如果我从文件加载它 - 它不会...我只是得到一个空数组。

我正在搜索的元素的深度级别是 5(如果我们说根节点是第一级)。当从字符串在 xml 上时 - 它甚至可以与从最后一个级别开始的 xpath 表达式一起使用......当从文件使用 xml 时 - 根本没有 xpath 工作。

我尝试将 xml 内容加载到 SimpleXMLElement 对象中的方式是(并应用xpath()):

1.

$xml = simplexml_load_file('filepath/file.xml');
$result = $xml->xpath('//Export/Product/Settings/Info[@Art="Short"]/@Something');

阿拉伯数字。

$xmlStr = file_get_contents('filepath/file.xml'); 
$xml = new SimpleXMLElement($xmlStr);
$result = $xml->xpath('//Export/Product/Settings/Info[@Art="Short"]/@Something');

不成功,他们两个...当从字符串只是$xml = simplexml_load_string($xmlStr);工作正常。我浏览了这篇文章,可能尝试了评论中几乎任何对我的情况来说合理的建议。

我注意到的另一件奇怪的事情是,当我在日志中写入$xml时,当它来自字符串时,我从Product深度级别(第 2 个)获得输出(数组和对象等)。但是当我使用从文件加载的$xml执行此操作时 - 我从根节点获取输出。

XML 代码的简单表示形式:

<Export>
  <Product>
    ...a lot of other elements...
    <Settings>
      <Info Art="Short" Something="blahblahblah"/>
      <Info Art"asda" Somethig="dsad"/>
      <Info .... />
      ...
    </Settings>
  </Product>
</Export>

所以我的问题是 - 当我从文件加载 XML 时如何让它工作,就像我从字符串加载它时它一样?

附言我不知道这是否与当前问题有关,但是 - 当我从字符串 (heredoc) 加载并且字符串作为第一行<?xml version="1.0" encoding="UTF-8"?>时 - 我收到在non-object上调用xpath()的错误。但是一旦我删除第一行,并且字符串从根节点开始 - 一切都完美无缺。

更新:第一个<Export...>节点:

<Export xmlns="http://something" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://something C:/some_path/some_file.xsd" GA_Vertriebsweg="2" KomplettExport="true">

更新2:从文件加载的整个事情不起作用,因为<Export...中的第1个属性如下所示:<Export xmlns="http://www.evelopment.de/schema/katalogexport/komplett"...>,所以整个问题都在命名空间中。

我已经测试了你的代码,它工作得很好。

Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [Something] => blahblahblah ) ) )

只有 2 个更改。

  1. 您删除了 xml 中的第一行<?xml version="1.0" encoding="UTF-8"?>
  2. 您缺少等号 <Info Art"asda" Somethig="dsad"/> 应该是 <Info Art="asda" Somethig="dsad"/>

要使 XML 正常工作,必须注册命名空间前缀:

$xml->registerXPathNamespace("w", "http://something");

您可以在此处阅读更多内容:链接

相关文章: