SimpleXMLElement for PHP array

The $d variable goes from the file_get_contents function to the URL.

 $answer = @new SimpleXMLElement($d); 

Below is the output of print_r($answer) :

 SimpleXMLElement Object ( [Amount] => 2698 [Status] => OK [State] => FL [Country] => USA ) 

How can I get the value of each element and add to the array? I can’t figure it out.

+18
arrays xml php simplexml
Apr 28 '10 at 2:35 a.m.
source share
5 answers

$answer can already work as an array. You can do this if you want to put it in a real array,

 $array = array(); foreach($answer as $k => $v) { $array[$k] = $v; } 
+10
Apr 28 '10 at 2:50
source share

In this simple case, type casting will also be performed:

 $my_array = (array)$answer 
+44
Apr 28 '10 at 3:01
source share

This should work:

 $xml = simplexml_load_string($xmlstring); $json = json_encode($xml); $array = json_decode($json,TRUE); 
+36
Mar 08 '15 at 22:07
source share

I have a problem with this function, because typing each XML child into an array can be problematic when the text is between the CDATA tags.

I fixed this by checking if the result of casting to an array is empty. If so, enter it in the string and you will get the correct result.

Here is my modified version with CDATA support:

 function SimpleXML2ArrayWithCDATASupport($xml) { $array = (array)$xml; if (count($array) === 0) { return (string)$xml; } foreach ($array as $key => $value) { if (!is_object($value) || strpos(get_class($value), 'SimpleXML') === false) { continue; } $array[$key] = SimpleXML2ArrayWithCDATASupport($value); } return $array; } 
+3
Jul 23 '14 at 19:57
source share

this function parses xml simpleXML recursive recursive array

 function SimpleXML2Array($xml){ $array = (array)$xml; //recursive Parser foreach ($array as $key => $value){ if(strpos(get_class($value),"SimpleXML")!==false){ $array[$key] = SimpleXML2Array($value); } } return $array; } 
0
Dec 18 '13 at 13:46 on
source share



All Articles