In Web development, XML and array formats are often used to store and transmit data. XML is a markup language that is often used for data description and interactive transmission, while arrays are a data structure that are often used for data processing and operations in programs. In the PHP language, we can convert PHP to XML and arrays, and this conversion is very convenient and fast.
This article mainly introduces the mutual conversion methods between PHP, XML and arrays in PHP, including the conversion methods from XML to arrays and from arrays to XML.
1. Mutual conversion between PHP and XML
In PHP, we can use the SimpleXML extension to realize mutual conversion between PHP and XML. SimpleXML is a PHP built-in extension for processing data in XML files. It can convert XML files into PHP objects or arrays, and also convert PHP objects or arrays into XML files.
- Convert XML file to PHP array
To convert XML file to PHP array, you need to use the simplexml_load_file function in the SimpleXML extension. The simplexml_load_file function can read the XML file at the specified path and return a SimpleXMLElement object, and then convert the information in the XML file into a PHP array by traversing the SimpleXMLElement object.
The following is a code example to convert an XML file into a PHP array:
$xmlStr = <menu> <item> <name>Chicken Curry</name> <price>8.95</price> <description>A spicy dish with chicken, carrots, and potatoes</description> </item> <item> <name>Beef Stir Fry</name> <price>10.95</price> <description>A savory dish with beef, mushrooms, and peppers</description> </item> </menu> XML; $xml = simplexml_load_string($xmlStr); $menu = []; foreach ($xml->item as $item) { $menu[] = [ 'name' => (string) $item->name, 'price' => (float) $item->price, 'description' => (string) $item->description, ]; } print_r($menu);
Run the above code, the output result is:
Array ( [0] => Array ( [name] => Chicken Curry [price] => 8.95 [description] => A spicy dish with chicken, carrots, and potatoes ) [1] => Array ( [name] => Beef Stir Fry [price] => 10.95 [description] => A savory dish with beef, mushrooms, and peppers ) )
- Convert a PHP array To convert a PHP array into an XML file
, the data in the array needs to be organized according to the syntax rules of XML. In PHP, we can use the SimpleXMLElement class to create XML elements, and use a foreach loop to iterate through the data in the array, add the data to the XML elements one by one, and finally output or save the XML file to a specified location through the asXML method of the SimpleXMLElement object. .
The following is a code example to convert a PHP array into an XML file:
$menu = [ [ 'name' => 'Chicken Curry', 'price' => 8.95, 'description' => 'A spicy dish with chicken, carrots, and potatoes' ], [ 'name' => 'Beef Stir Fry', 'price' => 10.95, 'description' => 'A savory dish with beef, mushrooms, and peppers' ] ]; $xml = new SimpleXMLElement('<menu></menu>'); foreach ($menu as $item) { $menuItem = $xml->addChild('item'); $menuItem->addChild('name', $item['name']); $menuItem->addChild('price', $item['price']); $menuItem->addChild('description', $item['description']); } $xmlStr = $xml->asXML(); echo $xmlStr;
Run the above code, the output result is:
<?xml version="1.0"?> <menu> <item> <name>Chicken Curry</name> <price>8.95</price> <description>A spicy dish with chicken, carrots, and potatoes</description> </item> <item> <name>Beef Stir Fry</name> <price>10.95</price> <description>A savory dish with beef, mushrooms, and peppers</description> </item> </menu>
2. Interaction between PHP and arrays Conversion
In PHP, we can use the json_encode and json_decode functions to convert PHP to arrays. The json_encode function converts an array in PHP to a JSON-formatted string and returns the converted string; the json_decode function converts a JSON-formatted string into an array in PHP.
- Convert a PHP array to a string in JSON format
To convert a PHP array into a string in JSON format, you need to use the json_encode function. The json_encode function can convert an array in PHP into a JSON-formatted string and return a value representing the JSON string.
The following is a code example to convert a PHP array into a string in JSON format:
$menu = [ [ 'name' => 'Chicken Curry', 'price' => 8.95, 'description' => 'A spicy dish with chicken, carrots, and potatoes' ], [ 'name' => 'Beef Stir Fry', 'price' => 10.95, 'description' => 'A savory dish with beef, mushrooms, and peppers' ] ]; $json = json_encode($menu); echo $json;
Run the above code, the output result is:
[{"name":"Chicken Curry","price":8.95,"description":"A spicy dish with chicken, carrots, and potatoes"},{"name":"Beef Stir Fry","price":10.95,"description":"A savory dish with beef, mushrooms, and peppers"}]
- Will Convert a string in JSON format to a PHP array
To convert a string in JSON format into a PHP array, you need to use the json_decode function. The json_decode function can convert a JSON-formatted string into an array in PHP and return a value representing the PHP array.
The following is a code example to convert a JSON formatted string into a PHP array:
$json = '[{"name":"Chicken Curry","price":8.95,"description":"A spicy dish with chicken, carrots, and potatoes"},{"name":"Beef Stir Fry","price":10.95,"description":"A savory dish with beef, mushrooms, and peppers"}]'; $menu = json_decode($json, true); print_r($menu);
Run the above code, the output result is:
Array ( [0] => Array ( [name] => Chicken Curry [price] => 8.95 [description] => A spicy dish with chicken, carrots, and potatoes ) [1] => Array ( [name] => Beef Stir Fry [price] => 10.95 [description] => A savory dish with beef, mushrooms, and peppers ) )
3. PHP and Mutual conversion of XML arrays
In PHP, we can use the SimpleXML extension and the json_encode/json_decode function to achieve mutual conversion between PHP, XML and arrays. Specifically, we can first convert the XML file into a PHP array, and then convert the PHP array into a JSON-formatted string; similarly, we can also convert a JSON-formatted string into a PHP array, and then convert the PHP array into a SimpleXMLElement Object, and finally get an XML file.
The following is a complete code example for conversion between PHP and XML arrays:
$xmlStr = <menu> <item> <name>Chicken Curry</name> <price>8.95</price> <description>A spicy dish with chicken, carrots, and potatoes</description> </item> <item> <name>Beef Stir Fry</name> <price>10.95</price> <description>A savory dish with beef, mushrooms, and peppers</description> </item> </menu> XML; // 将XML文件转换为PHP数组 $xml = simplexml_load_string($xmlStr); $menu = []; foreach ($xml->item as $item) { $menu[] = [ 'name' => (string) $item->name, 'price' => (float) $item->price, 'description' => (string) $item->description, ]; } // 将PHP数组转换为JSON格式的字符串 $json = json_encode($menu); // 将JSON格式的字符串转换为PHP数组 $menu = json_decode($json, true); // 将PHP数组转换为SimpleXMLElement对象 $xml = new SimpleXMLElement('<menu></menu>'); foreach ($menu as $item) { $menuItem = $xml->addChild('item'); $menuItem->addChild('name', $item['name']); $menuItem->addChild('price', $item['price']); $menuItem->addChild('description', $item['description']); } // 输出XML文件 $xmlStr = $xml->asXML(); echo $xmlStr;
Run the above code, the output result is:
<?xml version="1.0"?> <menu> <item> <name>Chicken Curry</name> <price>8.95</price> <description>A spicy dish with chicken, carrots, and potatoes</description> </item> <item> <name>Beef Stir Fry</name> <price>10.95</price> <description>A savory dish with beef, mushrooms, and peppers</description> </item> </menu>
Summary
The above is the method of converting PHP to XML and arrays, which is very simple and practical. Whether in front-end or back-end data transmission or data processing, we can perform corresponding conversions according to actual needs. It should be noted that when converting between XML and arrays, pay attention to the structure and format of the data to avoid unnecessary errors.
The above is the detailed content of How to convert php+xml and array to each other. For more information, please follow other related articles on the PHP Chinese website!

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
