How to convert an XML FIle into a SimpleXMLElement() Array?
I have an XML File:
<?xml version="1.0" encoding="iso-8859-1"?>
<deadlines>
<deadline>
<date>2010-07-01</date>
<text>Residency Application for Fall Due</text>
</deadline>
<deadline>
<date>2010-06-01</date>
<text>Residency Application for Summer Due</text>
</deadline>
<deadline>
<date>2010-07-20</date>
<text>Summer Bill Due</text>
开发者_如何学Python </deadline>
</deadlines>
When I load the file into a PHP script using simplexml_load_file(), I get the following:
SimpleXMLElement Object
(
[deadline] => Array
(
[0] => SimpleXMLElement Object
(
[date] => 2010-07-01
[text] => Residency Application for Fall Due
)
[1] => SimpleXMLElement Object
(
[date] => 2010-06-01
[text] => Residency Application for Summer Due
)
[2] => SimpleXMLElement Object
(
[date] => 2010-07-20
[text] => Summer Bill Due
)
)
)
In order for my script to handle the XML file as an array, I need to parse the file and get it into this format:
Array
(
[0] => SimpleXMLElement Object
(
[date] => 2010-07-01
[text] => Residency Application for Fall Due
)
[1] => SimpleXMLElement Object
(
[date] => 2010-06-01
[text] => Residency Application for Summer Due
)
[2] => SimpleXMLElement Object
(
[date] => 2010-07-20
[text] => Summer Bill Due
)
)
IS there a PHP function to convert the XML file? Thanks
$deadlines = array();
$sxe = new SimpleXmlElement($xml);
foreach($sxe->deadline as $deadline) {
$deadlines[] = $deadline;
}
print_r($deadlines);
or
$sxe = (array) new SimpleXmlElement($xml);
print_r( $sxe['deadline'] );
EDIT sorry, I assumed you were familiar enough with SimpleXml to know that the constructor of SimpleXmlElement assumes you are passing the XML as a string. Either change the line to read
$sxe = new SimpleXmlElement($filename, NULL, TRUE);
or replace it with
$sxe = simplexml_load_file($filename);
Easiest way of doing it.
<?php
$data = (array)simplexml_load_file('data.xml');
$data = array_pop($data);
print_r($data);
?>
精彩评论