Interpreting XML file tags with PHP

3

I'm having trouble interpreting an XML file with PHP. The difficulty I have is not being able to get the values according to your tag. The xml loop brings that difficulty to me. Here's a summary of it:

<?xml version="1.0"?>
<root>
    <id_couponoffer>
        <value>
            <![CDATA[192756]]>
        </value>
    </id_couponoffer>
    <title>
        <value>
            <![CDATA[Fast Runner]]>
        </value>
    </title>
    <startdate>
        <value>
            <![CDATA[2016-11-30]]>
        </value>
    </startdate>
    <enddate>
        <value>
            <![CDATA[2017-03-31]]>
        </value>
    </enddate>
    <url>
        <value>
            <![CDATA[http://v2.afilio.com.br/tracker.php?banid=4295676&campid=26275;2043&siteid=32790]]>
        </value>
    </url>
    <discount>
        <value>
            <![CDATA[0]]>
        </value>
    </discount>
    <progid>
        <value>
            <![CDATA[2043]]>
        </value>
    </progid>
    <rule>
        <value>
            <![CDATA[Oferta]]>
        </value>
    </rule><code><value><![CDATA[sem]]></value></code>
    <description>
        <value>
            <![CDATA[Lançamento: TÊNIS HOKA M BONDI 4 Por R$ 899,90]]>
        </value>
    </description>
    <type>
        <value>
            <![CDATA[n]]>
        </value>
    </type>
</root>

I'm not able to use foreach to get only some values.

$xml = simplexml_load_file('http://v2.afilio.com.br/api/feedproducts.php?token=53e355fe881a30.10592737&mode=dl&siteid=32790&affid=26275&format=XML');

foreach ($xml as $result) {

    echo $result->value;
    echo '</br>';
}

When I use $ result-> value, it pulls all xml values. What I want is to get just a few and organize them.

How can I do this?

    
asked by anonymous 06.01.2017 / 14:18

1 answer

2

You can use Xpath for this:

<?php
$dom = new DOMDocument();
$xml = "data_export.xml";
$dom->load($xml); 
$xpath = new DOMXPath($dom);
$items = $xpath->query('/root/id_couponoffer');
for($i = 0; $i < $items->length; $i++)
{
    $id_couponoffer = $xpath->query('/root/id_couponoffer');
    echo "id_couponoffer    :".$id_couponoffer->item($i)->nodeValue."<br/>";

    $title = $xpath->query('/root/title');
    echo "title :".$title->item($i)->nodeValue."<br/>";

    $startdate = $xpath->query('/root/startdate');
    echo "startdate :".$startdate->item($i)->nodeValue."<br/>";
}
echo "E assim por diante....";
?>

Take a look at this question (note that it uses html rather than xml) and see other ways to implement it.

    
06.01.2017 / 14:53