【问题标题】:Error loading xml in php (not absolute)在 php 中加载 xml 时出错(不是绝对的)
【发布时间】:2012-06-14 18:14:24
【问题描述】:

我正在尝试加载具有多个命名空间声明的 XML 文档 我的 php 是:

<?php 
$doc = new DOMDocument('1.0','UTF-8'); 
$doc->load( 'UBLCatalog.xml' ); 

$Items = $doc->getElementsByTagNameNS( "UBLCommonAggregateComponents","Item" ); 
foreach( $Items as $Item ) 
{ 
 $descriptions = $Item->getElementsByTagNameNS( "UBLCommonBasicComponents","Description" ); 
 $description = $descriptions->item(0)->nodeValue;  

 echo "<b>$description\n</b><br>"; 
 } 
?> 

错误是:

xmlns: URI UBLDatalogDocument 不是绝对的 file:///C:/wamp/www/XMLExperiments/UBLCatalog.xml,

我得到了输出,但是这个错误很烦人。

逐字记录错误是: 注意:DOMDocument::load() [domdocument.load]: xmlns: URI UBLDatalogDocument is not absolute in file:///C:/wamp/www/XMLExperiments/UBLCatalog.xml, line: 4 在 C:\wamp\www\XMLExperiments\ItemsXml.php 第 3 行

而且,如果我删除默认命名空间 (xmlns="UBLCatalogDocument"),错误就会消失

【问题讨论】:

  • 你能把XML格式分享在这里给别人看看。有助于理解结构。
  • 是哪一行导致了这个错误?

标签: php xml namespaces


【解决方案1】:

PHP XML 扩展(DOM、XMLReader、SimpleXml 等)use libxml library 用于解析 XML 文件。

这个错误的原因是 libxml 需要xmlns 属性中的绝对 URL(即xmlns="http://example.com/some-unique-url"),但只获取文本(xmlns="UBLCatalogDocument")。

来自libxml webpage

命名空间值必须是绝对 URL,但 URL 不是 必须指向 Web 上的任何现有资源。

因此,如果可能,请将您的 xmlns 属性更改为某个绝对 URL。

【讨论】:

    【解决方案2】:

    使用 XPath 查找节点可能会消除您的错误:

    $xpath = new DOMXpath($doc);
    $Items = $xpath->query('//item[@xmlns="UBLCommonAggregateComponents"]');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2012-06-24
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 2010-12-17
      相关资源
      最近更新 更多