开发者

Using DOMDOcument in PHP to parse XML and return an array of tree structure

I am very sorry if my question doesn't make sense as this is my first question, however i've been going through the questions posted for a while now.

right i have a XML structure of

<category>
  <id>123456</id>
  <name>Sales</name>
<categories>
  <category>
    <id>2345</id>
    <name>UK House prices</name>
  </category>
  <category>
    <id>3456</id>
    <name>Property Market Surveys</name>
  </category>
</categories>

I'd want a function to parse through the above xml and generate an array idealy to look something like this

array(
  "123456" => 
  array(
    "id" => "2345",
    "name" => "UK House prces",
  ),
  array(
    "id" => "3456",
    "name" => "Property Market Surveys",
  )
);

i must then be able to extract data of the array and insert it into a table with parent child relation.

Please 开发者_C百科let me know if you need more info to make this question complete.

Thanks a lot for your time.

Regards.


Why do you need it? If you want to access the XML tree in a simple fashion (similar to arrays, except array notation is only used when there are siblings with the same element name, otherwise the property notation is used), you can use SimpleXML.


This function seems to work, if you google php xml to array you get loads of good relevant results back. Here is a good starting point: (sourced from http://snipplr.com/view/17886/xml-to-array/)

Just specify the XML as the parameter and it returns an array:

function xml2array($xml,$recursive = false) {

 if (!$recursive ) { $array = simplexml_load_string ($xml); }
 else { $array = $xml ; }

 $newArray = array();
 $array = $array ;

 foreach ($array as $key => $value) {
     $value = (array) $value;

     if (isset($value[0])) { $newArray[$key] = trim($value[0]); }
     else { $newArray[$key][] = XML2Array($value,true) ; }
 }

 return $newArray;
}


Rewriting the last solution with a better indexing of nodes ( by name ) and reducing the number of parameters :

function xml2Array( $xml )
{
    $xml = ( array )( is_string( $xml ) ? simplexml_load_string( $xml ) : $xml ) ;

    $parse = array() ;
    foreach( $xml as $key => $value )
    {
        $parse[$key] = is_string( $value ) 
            ? trim( $value ) 
            : $this->xml2Array( $value )
        ;
    }

    return $parse ;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜