开发者

SimpleXMLElement to PHP Array [duplicate]

This question already has answers here: Recursive cast from SimpleXMLObject to Array (7 answers) 开发者_如何学运维 Closed 7 years ago.

Variable $d comes from file_get_contents function to a URL.

$answer = @new SimpleXMLElement($d);

Below is output of the print_r($answer):

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

How can I retrieve value of each element and add to an array? I can't figure it out.


In this simple case type casting will also work:

$my_array = (array)$answer


This should work:

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);


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

$array = array();
foreach($answer as $k => $v) {
  $array[$k] = $v;
}


I have a problem with this function because typecasting every XML child to an array can be problematic when the text is between CDATA tags.

I fixed this by checking if the result of the typecasting to an array is empty. If so typecast it to a string and you will get a proper 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;
}


this function parse a xml simpleXML recursive to array recursive

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜