Home Backend Development PHP Problem How to convert php+xml and array to each other

How to convert php+xml and array to each other

Apr 26, 2023 am 10:28 AM

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.

  1. 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 = <<<XML
<?xml version=&#39;1.0&#39;?>
<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);
Copy after login

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
        )

)
Copy after login
Copy after login
  1. 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;
Copy after login

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>
Copy after login
Copy after login

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.

  1. 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;
Copy after login

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"}]
Copy after login
  1. 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);
Copy after login

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
        )

)
Copy after login
Copy after login

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 = <<<XML
<?xml version=&#39;1.0&#39;?>
<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;
Copy after login

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>
Copy after login
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

PHP Input Validation: Best practices. PHP Input Validation: Best practices. Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

See all articles