Jump to content

How to read ALL data with XPath/XML/PHP from XML


PriteshP23

Recommended Posts

Hello All,

I would like to get all Equipment values. I have used DOM Document. It is reading ONLY LAST Element.
Equipment Id: 28.

I need all three.

Thanks in advanced.

XML File:

<?xml version="1.0" encoding="UTF-8"?>
-<Physical> 
<Catalog> 
</Catalog> 
-<Installed> 
-<Equipment> 
<Id>26</Id>
<Ref>Tew12</Ref>
-<Characteristic>
    <CharacteristicName>Height</CharacteristicName>    
    <CharacteristicValue>160</CharacteristicValue>
 </Characteristic>
 -<Characteristic>
     <CharacteristicName>Tilt</CharacteristicName>    
     <CharacteristicValue>30</CharacteristicValue> 
</Equipment> 
-<Equipment> 
<Id>27</Id>
<Ref>Tew13</Ref>
-<Characteristic>
    <CharacteristicName>Height</CharacteristicName>    
    <CharacteristicValue>165</CharacteristicValue>
 </Characteristic>
 -<Characteristic>
     <CharacteristicName>Tilt</CharacteristicName>    
     <CharacteristicValue>50</CharacteristicValue> 
</Equipment> 
-<Equipment> 
<Id>28</Id>
<Ref>Tew14</Ref>
-<Characteristic>
    <CharacteristicName>Height</CharacteristicName>    
    <CharacteristicValue>190</CharacteristicValue>
 </Characteristic>
 -<Characteristic>
     <CharacteristicName>Tilt</CharacteristicName>    
     <CharacteristicValue>50</CharacteristicValue> 
</Equipment> 
</Installed> 
</Physical>
Expected Result:
 
Id 26
Tilt 30
 
Id 27
Tilt 50
 
Id 28
Tilt 50
 
For the moment, i am trying to get all Ids values. Still it is not giving ALL Ids.
 
It should give Ids: 26 27 28
 
$Equipments = $dom->getElementsByTagName('Equipment');
foreach( $Equipments as $Equipments )
{
    $Ids = $Equipments->getElementsByTagName( 'Id' );
    $Id = $Ids->item(0)->nodeValue;
    echo $Id;
} 

 

try SimpleXML

$xml = simplexml_load_file('equip.xml');
foreach ($xml->xpath('//Equipment') as $eq) {
    echo "ID: {$eq->Id}<br>";
    foreach ($eq->Characteristic as $c) {
        if ($c->CharacteristicName == 'Tilt') {
            echo "Tilt: {$c->CharacteristicValue}<br>";
        }
    }
    echo '<br>';
}

 

@Barand:

 

First of all thanks for your time.

 

It is giving all IDs. But it not working for Tilt values. :confused:

 

 

 

 

 

Odd. After fixing the XML, my output was

ID: 26
Tilt: 30

ID: 27
Tilt: 50

ID: 28
Tilt: 50

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.