0

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

我正在搜索的元素的深度级别是 5(如果我们说根节点是 1 级)。当使用来自字符串的 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');

2.

$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)。但是当我$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 时如何让它工作,当我从字符串加载它时它工作?

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

更新:第一个<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...这里的第一个属性:<Export xmlns="http://www.evelopment.de/schema/katalogexport/komplett"...>,所以整个问题都在命名空间中。

4

1 回答 1

0

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

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");

你可以在这里阅读更多:链接

于 2013-10-18T13:30:34.357 回答