views:

235

answers:

2

Hello there,

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 let me know if you need more info to make this question complete.

Thanks a lot for your time.

Regards.

+1  A: 

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.

Artefacto
hey there, sorry for the late reply....but yeah you're right i did manage to use simplexml and kinda created a function similar to the one shown below by Chief17.I've managed to convert the xml into an array the way i wanted....i shall try and use that array to insert the data into the table and that will have a parent child relation within the same table.let me see how that goes, anyway thanks very much for your time and efforts...you guys are amazing....
bharath
A: 

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;

}

Chief17
hello thanks very much for your time, i've managed to create a function similar to this but the way i wanted it. i've got what i wanted so far....lets see how the rest of it goes. cheers mate.
bharath