首先,要将xml数据转换为数组,需要使用php中的一个内置函数simplexml_load_string()。这个函数可以将一个xml字符串载入到php中并解析它,返回一个simplexmlelement实例。simplexmlelement是php中专门用于处理xml数据的类,它包含了很多有用的方法来遍历和操作xml数据。
假设我们有以下这段xml数据:
<?xml version="1.0" encoding="utf-8"?><bookstore> <book category="children"> <title lang="en">harry potter</title> <author>j.k. rowling</author> <price>29.99</price> </book> <book category="fiction"> <title lang="en">the hunger games</title> <author>suzanne collins</author> <price>22.99</price> </book></bookstore>
我们可以使用simplexml_load_string()函数将它载入到php中:
$xml = '<?xml version="1.0" encoding="utf-8"?> <bookstore> <book category="children"> <title lang="en">harry potter</title> <author>j.k. rowling</author> <price>29.99</price> </book> <book category="fiction"> <title lang="en">the hunger games</title> <author>suzanne collins</author> <price>22.99</price> </book> </bookstore>';$xmlobj = simplexml_load_string($xml);
现在$xmlobj就是一个simplexmlelement实例,我们可以使用它的方法来遍历和操作xml数据。但是,如果我们需要对xml数据进行进一步的处理,例如对某些节点进行筛选、排序等操作,使用simplexmlelement就不太方便了。因此,我们需要将它转换为数组。
将simplexmlelement转换为数组非常简单,只需要在对象前加上一个(array)强制类型转换即可:
$xmlarr = (array) $xmlobj;print_r($xmlarr);
以上代码会输出以下结果:
array( [book] => array ( [0] => array ( [@attributes] => array ( [category] => children ) [title] => array ( [@attributes] => array ( [lang] => en ) [0] => harry potter ) [author] => j.k. rowling [price] => 29.99 ) [1] => array ( [@attributes] => array ( [category] => fiction ) [title] => array ( [@attributes] => array ( [lang] => en ) [0] => the hunger games ) [author] => suzanne collins [price] => 22.99 ) ))
可以看到,我们得到了一个二维数组,其中每个节点都被转换为了一个关联数组。如果xml数据中有多个具有相同名称的节点,它们会被转换为一个数组,例如这里的两本书都被转换为了一个book数组。
需要注意的是,转换后的数组中,每个节点都有一个名为@attributes的键,它对应了节点的属性。例如,book节点有一个category属性,它的值被转换为了@attributes['category']键的值。
此外,由于simplexmlelement是一个递归的结构,它包含了许多嵌套的子节点。因此,转换后的数组也是一个递归的结构,其中每个子数组对应了一个子节点。
当然,如果xml数据中有一些特殊的节点需要特殊处理,例如cdata节点、空节点等,就需要使用一些特殊的方法来处理了。但是对于普通的xml数据,使用simplexml_load_string()和(array)强制类型转换已经足够方便地将xml数据转换为数组了。
以上就是php怎么将xml转数组的详细内容。
