Home > Back-end >  How to loop a specific XML content in php?
How to loop a specific XML content in php?

Time:01-05

I have a response in XML format and I need to loop through the contents in PHP. As I am new to XML, I tried but cannot find any solutions. Can anyone help?

<?php
$xmlstring=<<<XML
<?xml version="1.0" encoding="utf-8"?>
<v-ov version="1.0">
<object vk="1" model="top">
<field type="BigIntegerField" name="bolpo">678</field>
<field name="pdop">
<object wk="1" model="stage">
<field type="DateTimeField" name="updated_on">10 Dec, 2020, 10:00 </field>
</object>
<object wk="2" model="stage">
<field type="DateTimeField" name="updated_on">11 Dec, 2020, 10:00 </field>
</object>
</field>
</object>
</v-ov>
XML;

$xpath = new SimpleXMLElement($xmlstring);
$node = $xpath->xpath('/object[@model="top"]/field[@name="pdop"]/object');
print_r($node);

CodePudding user response:

Your xpath is slightly off for selecting the object nodes. There is a <v-ov> node at the XML root but your xpath is saying <object> is the root as the xpath begins with a single slash.

If you change your xpath to include a double slash at the start then the xpath engine will look for the nodes at any depth, ie: //object[@model="top"]/field[@name="pdop"]/object

With the nodes selected you can iterate over them with a foreach to pull out any values you need:

$xml_obj = new SimpleXMLElement($xmlstring);
$nodes = $xml_obj->xpath('//object[@model="top"]/field[@name="pdop"]/object');
foreach($nodes as $node) {
    print_r($node);
    
    //attribute values
    $model = $node['model'];
    $wk = $node['wk'];
    
    //node value
    $field = $node->field;
    
}

Example here: https://3v4l.org/MUL4o#v8.2.1

CodePudding user response:

You may need a nested loop to access your XML content this is a simple example i can give

<?php

$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<v-ov version="1.0">
<object vk="1" model="top">
<field type="BigIntegerField" name="bolpo">678</field>
<field name="pdop">
<object wk="1" model="stage">
<field type="DateTimeField" name="updated_on">10 Dec, 2020, 10:00 </field>
</object>
<object wk="2" model="stage">
<field type="DateTimeField" name="updated_on">11 Dec, 2020, 10:00 </field>
</object>
</field>
</object>
</v-ov>
XML;

$xml_obj = simplexml_load_string($xml);

foreach($xml_obj as $node) {
    print_r($node);
}

?>
  •  Tags:  
  • php
  • Related