mysql xml字符串转数组_php如何将xml转为array数组

方法:首先用simplexml_load_string()将XML字符串转换为SimpleXMLElement对象;然后用json_encode()将该对象转换为JSON数据;最后用json_decode()将JSON数据转换为数组即可。

22193e22d2222b95c3e24b6aac39078d.png

本教程操作环境:windows7系统、PHP7.1版,DELL G3电脑

php将xml转换为array数

1、函数:/*

@desc:xml转数组

@param data xml字符串

@return arr 解析出的数组

*/

function xmltoarray($data){

$obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);

$json = json_encode($obj);

$arr = json_decode($json, true);

return $arr;

}

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

json_encode() 用于对变量进行 JSON 编码,该函数如果执行成功返回 JSON 数据,否则返回 FALSE 。

json_decode() 函数用于对 JSON 格式的字符串进行解码,并转换为 PHP 变量(对象或数组)。json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

参数json_string: 待解码的 JSON 字符串,必须是 UTF-8 编码数据

assoc: 当该参数为 TRUE 时,将返回数组,FALSE 时返回对象。

depth: 整数类型的参数,它指定递归深度

options: 二进制掩码,目前只支持 JSON_BIGINT_AS_STRING 。

2、测试:

a. 代码:<?php

$string = <<Forty What?

Joe

Jane

I know that's the answer -- but what's the question?

XML;

$arr = xmltoarray($string);

var_dump($arr);

b. 输出:array(4) {

["title"]=>

string(11) "Forty What?"

["from"]=>

string(3) "Joe"

["to"]=>

string(4) "Jane"

["body"]=>

string(57) "

I know that's the answer -- but what's the question?

"

}

更多编程相关知识,请访问:编程视频!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值