PHP 将xml文件解析为数组

2022/8/23 1:52:46

本文主要是介绍PHP 将xml文件解析为数组,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

SimpleXML扩展在解析和操作XML文档时非常实用,本文将讨论如何使用php SimpleXML解析xml文件。

首先,让我们看一下使用SimpleXML扩展将XML内容转换为数组所需遵循的步骤。

  • 将xml文件转换为字符串:  使用php file_get_contents()函数将整个xml文件作为字符串读取并存储到变量中。
  • 将字符串转换为对象: 将字符串转换为对象,可以通过PHP的一些内置函数simplexml_load_string()轻松完成。
  • 将对象转换为JSON:  json_encode()函数将对象,数组的数据格式转换为json格式的数据
  • 解码JSON对象:  json_decode()函数解码JSON字符串。它将JSON编码的字符串转换为PHP变量。

 

php解析xml文件需要使用到的函数

file_get_contents():

file_get_contents() 函数把整个xml文件读入一个字符串中

simplexml_load_string():

simplexml_load_string() 函数转换形式良好的 XML 字符串为 SimpleXMLElement 对象。

simplexml_load_file():

simplexml_load_file() 函数把 XML 文档载入对象中。如果失败,则返回 false。

json_encode():

json_encode函数主要用来将数组和对象,转换为json格式。

json_decode():

json_decode函数用于将json文本转换为相应的PHP数据结构.

 

PHP将xml文件解析为数组 - 示例

xml文件abc.xml如下:
<?xml version='1.0'?>
<userdb>
   <firstname name='Alex'>
      <symbol>AL</symbol>
      <code>A</code>
   </firstname>
      <firstname name='Sandra'>
         <symbol>SA</symbol>
         <code>S</code>
   </firstname>
</userdb>

php代码:

<?php
// xml file path
   $path = "abc.xml";
   $xmlfile = file_get_contents($path);
   $new = simplexml_load_string($xmlfile);
   $jsonfile = json_encode($new);
   $myarray = json_decode($jsonfile, true);
   print_r($myarray);
?>

运行结果:

Array
(
   [firstname] => Array
       (
           [0] => Array
               (
                   [@attributes] => Array
                       (
                           [name] => Alex
                       )
                   [symbol] => AL
                   [code] => A
               )
           [1] => Array
               (
                   [@attributes] => Array
                       (
                           [name] => Sandra
                       )
                   [symbol] => SA
                   [code] => S
               )
       )
)

以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家


这篇关于PHP 将xml文件解析为数组的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程