Heim  >  Artikel  >  php教程  >  php解析xml文件的方法

php解析xml文件的方法

WBOY
WBOYOriginal
2016-06-06 19:47:351531Durchsuche

最近一段时间在做模板包导入。模板包中包含有xml文件,,需要解析成给定的php数组格式。 我接触到了两种方法,分别是DOMDocument 方法和 simple_load_file. 个人偏好后一种,因为简单。 下面是具体用法 $template_config_path = 'module_1.xml';function par

         最近一段时间在做模板包导入。模板包中包含有xml文件,,需要解析成给定的php数组格式。

    我接触到了两种方法,分别是DOMDocument 方法和 simple_load_file. 个人偏好后一种,因为简单。

 下面是具体用法

$template_config_path = 'module_1.xml';
function parseXMLConfig($template_config_path){
$myxml = simplexml_load_file($template_config_path);

return xmlToArray($myxml);
}

function xmlToArray($xml){
$arr_xml = (array)$xml;
foreach($arr_xml as $key=>$item){
if(is_object($item) || is_array($item)){
$arr_xml[$key] = xmlToArray($item);
}
}
return $arr_xml;
}
$test = parseXMLConfig($template_config_path);
print_r($test);

  其实DOMDocument 方法就是将xml转成dom对象,然后利用dom提供的方法,如getElementById ()进行相关的操作。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn