简体   繁体   中英

PHP DOMXPath Query by node name not finding anything

I'm trying to understand the basics of DOMXPath in PHP. I have an XML file that starts with what's below.

<?xml version="1.0"?>
<ListFinancialEventsResponse xmlns="http://mws.amazonservices.com/Finances/2015-05-01">
  <ListFinancialEventsResult>
    <FinancialEvents>
      <ShipmentEventList>
        <ShipmentEvent>

I'm trying to get the FinancialEvents tags using the below PHP with a few different xpath query attempts but neither works.

  $file = file_get_contents('file.xml');
  $dom = new DOMDocument();
  $dom->loadXML($file);

  $xpath = new DOMXPath($dom);
  $xpath->registerNamespace('m','http://mws.amazonservices.com/Finances/2015-05-01');

  $events = $xpath->query('FinancialEvents');  // Attempt 1
  $events = $xpath->query('m:FinancialEvents');// Attempt 2

According to the docs, these should return all nodes with name 'FinancialEvents'. I know that it works if I use the below xpath query

  $events = $xpath->query('//m:FinancialEvents');

So my question is, why don't my first 2 queries work? Isn't the element <FinancialEvents> also a node of the same name?

Thanks

Not tested but you could try:

$query='//ListFinancialEventsResult/FinancialEvents';
$events=$xp->query( $query );
if( !empty( $events ) && $events->length > 0 ){
    foreach( $events as $event ){
        echo $event->nodeValue;
    }
}

I suspect that the first couple of queries do not return a nodelist is because you are effectively trying to find nodes FinancialEvents at root level ~ if you supplied a reference node ( which would be a DOMNode ListFinancialEventsResult )for the query then it would work.

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