1

I have some PHP code that calls, then receives a response from an API (using file_get_contents()), the API responses with a XML format like so:

<?xml version="1.0"?>
<root><status>success</status>
<duration>5 seconds</duration>
<average>13692.4</average></root>

so for example in PHP how would i take this XML response and get (for lets say) the value of <average>? Any help would be greatly appreciated :)

C0d1ng
  • 441
  • 6
  • 17
  • Checkout the [function.xml-parse-into-struct](http://php.net/manual/en/function.xml-parse-into-struct.php) `Example #2 ` && `Example #3 ` – Murad Hasan May 10 '16 at 07:50

1 Answers1

1

There are several ways to parse XML, one of which is the XMLReader. A simple example to retrieve the value of average from the XML you posted would be something like this:

<?php

// Read the XML output from the API
$xml = file_get_contents('https://api.example.com/output.xml');

$reader = new XMLReader();
$reader->open('data://text/xml,' . $xml);

// Read the XML
while ($reader->read()) {
    // Look for the "average" node
    if ($reader->name == 'average') {
        $value = $reader->readString();
        if (!empty($value)) {
            // This will output 13692.4
            var_dump($value);
        }
    }
}

$reader->close();

A live example can be seen here: https://3v4l.org/s7sNl

Oldskool
  • 34,211
  • 7
  • 53
  • 66