【问题标题】:How to write a correct XPath for an XML on php?如何在 php 上为 XML 编写正确的 XPath?
【发布时间】:2018-06-19 06:44:45
【问题描述】:

我正在创建一个简单的 Web 应用程序来打印包含在使用 XPath 的 XML 测试文件中的一些信息。我在下面显示了这个 XML 文件(我已经指出了后面提到的一些重要值):

这个应用程序已经能够打印一些值,例如,如果我想在屏幕截图上打印绿色标记的值,我这样做:

foreach ($xml->xpath('//cfdi:Comprobante//cfdi:Emisor') as $emisor){
    echo("Emisor = ".$emisor['nombre']);
}

打印“Emisor = PHARMA PLUS SA DE CV”表示没关系,之后,我想打印红色标记的值,称为“UUID”,我这样做:

foreach ($xml->xpath('//cfdi:Comprobante//cfdi:Complemento//tfd:TimbreFiscalDigital') as 
$tfd){
    echo("UUID = ".$tfd['UUID']);
}

这给了我这个消息:SimpleXMLElement::xpath(): Undefined namespace prefix in /storage/ssd3...prueba4.php on line 46

我开始使用 XML 和 php,请你帮我编写正确的 XPath 吗?提前致谢。

XML 文件为:here

【问题讨论】:

    标签: php xml xpath


    【解决方案1】:

    在 XPath 中使用命名空间时,您应该使用 registerXPathNamespace() 将其注册到(在 SimpleXML 的情况下)文档中。

    所以...

    $xml->registerXPathNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital");
    foreach ($xml->xpath('//cfdi:Comprobante//cfdi:Complemento//tfd:TimbreFiscalDigital') as
            $tfd){
                echo("UUID = ".$tfd['UUID']).PHP_EOL;
    }
    

    给...

    UUID = ad662d33-6934-459c-a128-bdf0393e0f44
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多