简体   繁体   中英

How to get value of XML Element Attribute from xml file in php with DOMXPath

here is simple XML File and i need to get the value of unitCode and i am using DOMXPath object to get the values.

<cbc:ConsumerUnitQuantity unitCode="BX">
    80.000
</cbc:ConsumerUnitQuantity>

i have tried

$unitCode = $xpath->query('//cbc:ConsumerUnitQuantity [@unitCode=""]')->item(0);

You're missing the namespace. You XML elements have a namespace prefix, but you did not register one on the Xpath object. Check you document for a xmlns:cbc attribute.

$xml = <<<'XML'
<cbc:ConsumerUnitQuantity xmlns:cbc="your-namespace" unitCode="BX">
    80.000
</cbc:ConsumerUnitQuantity>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);

$xpath = new DOMXpath($dom);
$xpath->registerNamespace('ns-cbc', 'your-namespace');

var_dump(
  $xpath->evaluate('string(//ns-cbc:ConsumerUnitQuantity)', NULL, FALSE)
);

Unlike DOMXpath::query() , DOMXpath::evaluate() can return scalar values directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM