18910140161

php中xml转为数组的方法

2021-12-11 09:13:04

89

遇到了一个使用php脚本把XML格式的字符串转成数组的需求,下面就来写个转换的方法,记录下一下。

php xml字符串转数组的方法

php自定义一个 xml 转 数组的函数!

/**
 * php XML 转数组函数
 * @param string $xml XML格式的字符串
 * 
 * @return array 
 */
function xmltoarray($xml){
    // 将 XML 为 SimpleXMLElement 对象
    $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    // 转换为JSON
    $json = json_encode($obj);
    // 转换为数组
    $arr = json_decode($json, true);      
    return $arr;
}

调用自定义的函数,则可以使用 XML 转为 数组

$string = <<<XML
<?xml version='1.0'?> 
<document>
    <name>mochu</name>
    <pagehome>Joe</pagehome>
    <age>18</age>
</document>
XML;
$arr = xmltoarray($string);
print_r($arr);

打印结果:

Array
(
    [name] => mochu
    [pagehome] => Joe
    [age] => 18
)
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航