Get the values of the child nodes with PHP DOM

25,127

Solution 1

Try

$document_xml = new DOMDocument();
$document_xml->loadXML($xml);
$elements = $document_xml->getElementsByTagName('LISTING');
foreach ($elements as $node) {
    $idtest = $node->getElementsByTagName('DATEMAJ');
    $idElem = $node->getElementsByTagName('ID');
    $idList[] = $idElem->item(0)->nodeValue;
 }

See demo here

Solution 2

Use DOMXpath::evaluate().

$xml = <<<'XML'
<LISTINGS xmlns:diffgr="urn:digggr" xmlns:msdata="urn:msdata">
  <LISTING diffgr:id="LISTING1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
    <ID>ACCAMAQU0470001P</ID>
    <DATECREA>2013-01-28T09:45:21+01:00</DATECREA>
    <DATEMAJ>2014-01-09T17:41:25+01:00</DATEMAJ>
  </LISTING>
</LISTINGS>
XML;

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

$result = [];
foreach ($xpath->evaluate('//LISTING') as $listing) {
  $result[] = [
    'ID' => $xpath->evaluate('string(ID)', $listing),
    'DATEMAJ' => $xpath->evaluate('string(DATEMAJ)', $listing)
  ];
}

var_dump($result);

Output: https://eval.in/103310

array(1) {
  [0]=>
  array(2) {
    ["ID"]=>
    string(16) "ACCAMAQU0470001P"
    ["DATEMAJ"]=>
    string(25) "2014-01-09T17:41:25+01:00"
  }
}

WARNING: Your XML fragment contains several attributes with namespaces prefixes. So the XML is using namespaces. It id possible that here is a default namespace defined as well. If that is the case a namespace prefix for that namespace has to be registered and used.

Share:
25,127
BnJ
Author by

BnJ

Updated on July 09, 2022

Comments

  • BnJ
    BnJ almost 2 years

    Here is an example XML I use:

        <LISTING diffgr:id="LISTING1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
        <ID>ACCAMAQU0470001P</ID>
        <DATECREA>2013-01-28T09:45:21+01:00</DATECREA>
        <DATEMAJ>2014-01-09T17:41:25+01:00</DATEMAJ>
        ...
        </LISTING>
        ...
    

    In the PHP code, here I am:

    $document_xml = new DOMDocument();
    $document_xml->loadXML($retour['any']);
    $elements = $document_xml->getElementsByTagName('LISTING');
    
    while ($elements->item($i)) {
        $element = $elements->item($i); // On obtient le nœud 
        $list = $element->childNodes; // On récupère les nœuds avec childNodes
        $idtest = $element->getElementsByTagName('DATEMAJ');
        $idElem = $element->getElementsByTagName('ID');
        foreach($idElem as $idSirtaq){
            $idList[] = $idSirtaq->firstChild->nodeValue;
        }        
        foreach ($idtest as $test) {   
            //HERE
            ...
        }
        ...
     }
    

    I would to get the value of nodes "ID" and "DATEMAJ". I know to get the "DATEMAJ" value, with $test->firstChild->nodeValue, but not how to retrieve the value of the node "ID".