0
votes

How can I extract the values of an attributes parent and child via XPath?

A sample XML file is:

<?xml version="1.0" encoding="UTF-8"?>
<detail month="9" year="2018">
    <subService desc="Voice" parent="1" service="V">
        <item qnt="67" period="02" time="18:51" date="2018-09-04"></item>
        <item qnt="93" period="02" time="13:02" date="2018-09-07"></item>
    </subService>
    <subService desc="Voice" parent="11" service="V">
        <item qnt="60" period="02" time="11:09" date="2018-09-19"></item>
        <item qnt="60" period="02" time="10:19" date="2018-09-04"></item>
    </subService>
    <subService desc="Data" parent="55" service="D">
        <item qnt="7200" period="01" time="00:00" date="2018-09-14"></item>
        <item qnt="21600" period="01" time="00:00" date="2018-09-14"></item>
    </subService>
</detail>

Here is code I am using for collecting data from child but I need data from parent too.

<?php
$id=1; 
$xml=simplexml_load_file("./data/test3.xml") or die("Error: Cannot create object");
$result = $xml->xpath("//subService/item");    
foreach($result as $key => $value)  {
    $quantity=$value['qnt'];
    $period=$value['period'];
    $date=$value['time'];
    $time=$value['date'];
    echo "$id,$parent,$service,$quantity,$period,$date,$time <br>";
    $id=($id+1);
}
?> 

Here's what I'd like the output to be:

1,1,V,67,02,18:51,2018-09-04
2,1,V,93,02,13:02,2018-09-07 
3,11,V,60,02,11:09,2018-09-19
4,11,V,60,02,10:19,2018-09-04 
5,55,D,7200,01,00:00,2018-09-14 
6,55,D,21600,01,00:00,2018-09-14

Thank you very much

1

1 Answers

0
votes

I find it easier to start at the top level to fetch XML when using SimpleXML. This involves an extra loop - starting with <subService> elements and the an inner loop for each <item>. This makes the accessing of the various elements as simple (and obvious to future coders) as possible...

$result = $xml->xpath("//subService");
foreach($result as $value)  {
    $parent = $value['parent'];
    $service = $value['service'];
    foreach ( $value->item as $item )   {
        $quantity=$item['qnt'];
        $period=$item['period'];
        $date=$item['time'];
        $time=$item['date'];
        echo "$id,$parent,$service,$quantity,$period,$date,$time <br>";
        $id++;
    }
}

If this is your actual XML format, I would be tempted to remove the XPath altogether and go for...

//$result = $xml->xpath("//subService");
foreach($xml->subService as $value)  {