SimpleXMLElement 到 PHP 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2726487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SimpleXMLElement to PHP Array
提问by Codex73
Variable $dcomes from file_get_contentsfunction to a URL.
变量$d从file_get_contents函数到 URL。
$answer = @new SimpleXMLElement($d);
Below is output of the print_r($answer):
以下是输出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.
如何检索每个元素的值并添加到数组中?我想不通。
采纳答案by ZZ Coder
The $answercan already work as an array. You can do this if you want put it in a real array,
在$answer已经可以工作作为数组。如果你想把它放在一个真正的数组中,你可以这样做,
$array = array();
foreach($answer as $k => $v) {
$array[$k] = $v;
}
回答by dkinzer
In this simple case type casting will also work:
在这个简单的情况下,类型转换也可以工作:
$my_array = (array)$answer
回答by Damian Alberto Pastorini
This should work:
这应该有效:
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
回答by Bo Pennings
I have a problem with this function because typecasting every XML child to an array can be problematic when the text is between CDATAtags.
我对这个函数有一个问题,因为当文本位于CDATA标签之间时,将每个 XML 子项类型转换为数组可能会出现问题。
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 CDATAsupport:
这是我CDATA支持的修改版本:
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;
}
回答by user2960279
this function parse a xml simpleXML recursive to array recursive
此函数将 xml simpleXML 递归解析为数组递归
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;
}

