Search code examples
phpxmlxml-parsingsimplexmlresponse

PHP Get Total Sum Value From XML Response Tree


Im trying to get the total sum value from a specific xml tree like so:

Example response from 3rd party:

<response>
    <date_start>2014-02-01</date_start>
    <date_end>2014-02-25</date_end>
    <source>Web</source>
    <partners>
        <partner>
            <partner_id>99</partner_id>
            <number_of_leads>11</number_of_leads>
        </partner>
        <partner>
            <partner_id>101</partner_id>
            <number_of_leads>17</number_of_leads>
        </partner>
        <partner>
            <partner_id>103</partner_id>
            <number_of_leads>38</number_of_leads>
        </partner>
    </partners>
</response>

I would like the end result to be a variable like this: $lead_total = '66'; The repeating "partners" block could have anywhere from 1 to perhaps 100 partners listed. So I would like to be able to iterate thru all partners and display the number_of_leads sum.

So far Ive been doing it this way, which is ugly and not very expandable, and I have to create new file each time I add additional partner IDs to the query string below:

$target_url = 'https://........&Partner_ID=99,101,103.....';

$xml = simplexml_load_file($target_url);

$number_of_leads1 = $xml->partners->partner[0]->number_of_leads;
$number_of_leads2 = $xml->partners->partner[1]->number_of_leads;
$number_of_leads3 = $xml->partners->partner[2]->number_of_leads;

if(!$number_of_leads1) { $number_of_leads1 = '0'; }
if(!$number_of_leads2) { $number_of_leads2 = '0'; }
if(!$number_of_leads3) { $number_of_leads3 = '0'; }

$lead_total = $number_of_leads1 + $number_of_leads2 + $number_of_leads3;

header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: max-age=0 no-cache must-revalidate no-store');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo "
<root>
    <item> 
        <value>{$lead_total}</value> 
        <text>{$currenttime} CST, {$currentdate}</text>
    </item>
</root>
";

Im not very good at creating loops, or arrays, or more advance php, and such so any help to clean this mess up is greatly appreciated. Ideally, getting the total number_of_leads based on the Partner_IDs in the url string would be awesome. Thanks!


Solution

  • I think you can just loop in your xml file and sum all number_of_leads while looping as follow

    $xml = simplexml_load_file($target_url);
    $total=0;
    foreach($xml->partners->partner as $data)
    {    
        $total += $data->number_of_leads;
    }
    echo 'Total is: ' . $total;
    //output Total is: 66
    

    Live Working Demo

    Note in demo i used simple_load_xml_string because i placed your xml as a string, you are instead downloading as a file so use simple_load_xml_file as you did correctly