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

How to convert XML string to array in PHP?

Guanhui
GuanhuiOriginal
2020-07-22 10:02:572765browse

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);

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

$json_str = json_encode($obj);

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

$xml_arr = json_decode($json_str, true);

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);

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!

Statement:
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