Home > Backend Development > PHP Problem > How to convert XML string to array in PHP?

How to convert XML string to array in PHP?

Guanhui
Release: 2023-03-02 20:42:02
Original
2882 people have browsed it

How to convert XML string to array in PHP?

#How to convert XML string to array in PHP?

First use the function "simplexml_load_string()" to convert the XML string into an object;

$obj = simplexml_load_string($str,"SimpleXMLElement", LIBXML_NOCDATA);
Copy after login

Then use the "json_encode()" function to convert the object into a JSON string;

$json_str = json_encode($obj);
Copy after login

Finally use "json_decode()" to convert it to an array.

$xml_arr = json_decode($json_str, true);
Copy after login

Complete code

$str = '
      
      
    1472549042
      
      
      
      
      
      
      
      
      
      
';

$obj = simplexml_load_string($str,"SimpleXMLElement", LIBXML_NOCDATA);
$test = json_decode(json_encode($obj),true);
$arr = [
    'FromUserName' => $test['FromUserName'],
    'ToUserName' => $test['ToUserName'],
    'CreateTime' => $test['CreateTime'],
    'CardId' => $test['CardId'],
    'UserCardCode' => $test['UserCardCode'],
    'ConsumeSource' => $test['ConsumeSource'],
    'StaffOpenId' => $test['StaffOpenId']
];
$arr = array_map('trim',$arr);
var_dump($arr);
Copy after login

Recommended tutorial: "PHP"

The above is the detailed content of How to convert XML string to array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template