Method: First use simplexml_load_string() to convert the XML string into a SimpleXMLElement object; then use json_encode() to convert the object into JSON data; finally use json_decode() to convert the JSON data into an array.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php converts xml For the array number
1. Function:
/* @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() function converts a well-formed XML string into a SimpleXMLElement object.
json_encode() is used to JSON encode variables. This function returns JSON data if executed successfully, otherwise it returns FALSE.
json_decode() function is used to decode a JSON-formatted string and convert it into a PHP variable (object or array).
json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Parameters
- ##json_string: JSON string to be decoded, must be UTF-8 encoded data
- assoc: When this parameter is TRUE, an array is returned, and when FALSE, an object is returned.
- depth: Integer type parameter, which specifies the recursion depth
- options: Binary mask, currently only JSON_BIGINT_AS_STRING is supported.
2. Test:
<?php $string = <<<XML <?xml version='1.0'?> <document> <title>Forty What?</title> <from>Joe</from> <to>Jane</to> <body> I know that's the answer -- but what's the question? </body> </document> XML; $arr = xmltoarray($string); var_dump($arr);b. Output:
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? " }For more programming-related knowledge, please visit:
Programming Video! !
The above is the detailed content of How to convert xml to array in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
