user3707281
user3707281

Reputation: 89

Getting values from XML through PHP with muliple namespaces

I am trying to read from an XML file which uses 3 namespaces and struggling to read values from it.

<?xml version ="1.0"?> 
<Invoice xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"

<cac:PartyName>
<cbc:Name>John Doe</cbc:Name>
</cac:PartyName>

My PHP so far after reading several examples, been years since ive written PHP so probably so easy for you guys.

<?php

$xml = simplexml_load_file('file.xml');
$xml->registerXPathNamespace('cbc', 
'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2');
$xml->registerXPathNamespace('cac', 
  'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-
 2');

foreach($xml->xpath('//cac:PartyName') as $PartyName)
{
print_r ($PartyName->xpath('//cbc:Name')); 

}

?>

I register only two of the namespaces as they are the only ones in use in the XML file. (CBC and CAC). I get results from the entire array from this but i kinda want my output to be just "John Doe".

Upvotes: 1

Views: 912

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57121

Depending on how much other data you have and where other elements with the same name might be in the document depends on how specific your XPath can be.

foreach($xml->xpath('//cac:PartyName') as $PartyName)
{
    echo (string)$PartyName->children('cbc', true)->Name.PHP_EOL;
}

The above means that it will be all the data under the <PartyName> element and you can then pick out which bits you want.

foreach($xml->xpath('//cac:PartyName/cbc:Name') as $PartyName)
{
    echo (string)$PartyName.PHP_EOL;
}

This limits it to just pick out the Name elements directly under the PartyName elements, in case the Name elements might exist elsewhere.

Upvotes: 2

iainn
iainn

Reputation: 17417

You can access the text content of a SimpleXMLElement by just casting it to a string:

echo (string) $PartyName->xpath('//cbc:Name')[0];

Note the added [0] at the end of the line as well - the xpath method returns an array of objects, and we just need to refer to the first one.

See https://eval.in/945981

Upvotes: 1

Related Questions