bear
bear

Reputation: 11605

Breaking up an XML file

I've got an XML output that produces code such as:

<loadavg>
   <one>0.00</one>
   <five>0.02</five>
   <fifteen>0.02</fifteen>
</loadavg>
<!-- whostmgrd -->

I would like to know how I can use PHP to parse that file, and grab the contents between <one>,<five> and <fifteen>. It would be useful if it were to be stored as $loadavg[1] an array.

Thanks

Upvotes: 2

Views: 127

Answers (2)

Felix Kling
Felix Kling

Reputation: 816384

Yep, SimpleXML can do it:

$xml = <<<XML
    <loadavg>
        <one>0.00</one>
        <five>0.02</five> 
        <fifteen>0.02</fifteen>
    </loadavg>
XML;

$root = new SimpleXMLElement($xml);
$loadavg = array((string) $root->one, 
                 (string) $root->five, 
                 (string) $root->fifteen);

print_r($loadavg);

prints

Array (
   [0] => 0.00
   [1] => 0.02
   [2] => 0.02 
)

Upvotes: 3

Jeremy
Jeremy

Reputation: 2669

The easiest way to parse an XML file is using SimpleXML. It should be easy to load the XML as a SimpleXML object and get the data using that. If you could post a sample of a complete XML file I could offer some sample code.

Upvotes: 1

Related Questions