Home Backend Development PHP Problem How to convert xml returned by soap into an array in php

How to convert xml returned by soap into an array in php

Mar 31, 2023 am 09:09 AM

When using web services, when we use SOAP as the transmission protocol, we will receive a return result in XML format. Sometimes, we need to convert this XML data into an array so that we can use this data more conveniently. In PHP, this conversion is very simple and we can do it using PHP's built-in functions.

1. XML format example of SOAP return value

When using web services, we generally send requests through the SOAP protocol and get a return result in XML format. The returned results in XML format can be complex, but we can understand it with some examples. The following is a simple XML format example of a SOAP return value:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://localhost/webservice.php">
  <SOAP-ENV:Body>
    <ns1:response>
      <ns1:result>
        <name>John Smith</name>
        <age>30</age>
        <country>USA</country>
      </ns1:result>
      <ns1:result>
        <name>Alice Jones</name>
        <age>25</age>
        <country>UK</country>
      </ns1:result>
    </ns1:response>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Copy after login

The above XML code contains an example of a SOAP return value. Its root node is <SOAP-ENV:Envelope>, which contains a <SOAP-ENV:Body> node, <SOAP-ENV:Body&gt ;There is a <ns1:response> node in the node, and there are two <ns1:result> nodes in this node. Each <ns1:result> node contains three element nodes: <name>, <age> and <country&gt ;.

This XML return value contains the information of two people. We can convert it into an array through PHP to facilitate us to process this data.

2. Use PHP's simplexml_load_string() function to convert XML into an array

In PHP, we can use the built-in simplexml_load_string() function to convert XML into an array. In the above XML example, we can convert it to an array using the following PHP code:

$xmlstr = '<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://localhost/webservice.php">
  <SOAP-ENV:Body>
    <ns1:response>
      <ns1:result>
        <name>John Smith</name>
        <age>30</age>
        <country>USA</country>
      </ns1:result>
      <ns1:result>
        <name>Alice Jones</name>
        <age>25</age>
        <country>UK</country>
      </ns1:result>
    </ns1:response>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>';

$xml = simplexml_load_string($xmlstr);
$json = json_encode($xml);
$array = json_decode($json, true);

print_r($array);
Copy after login

In the above code, we first copy the XML string into the $xmlstr variable , and then use the simplexml_load_string() function to convert it to a PHP object. Next, we use the json_encode() and json_decode() functions to convert the PHP object into an array, and finally use the print_r() function to print out the array.

Run this code, we will get the following output:

Array
(
    [response] => Array
        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [name] => John Smith
                            [age] => 30
                            [country] => USA
                        )
                    [1] => Array
                        (
                            [name] => Alice Jones
                            [age] => 25
                            [country] => UK
                        )
                )
        )
)
Copy after login

The above output shows a PHP array, which contains the XML transformed data returned by SOAP. We can use this data very conveniently for processing.

3. Use PHP's SimpleXMLElement class

In addition to the simplexml_load_string() function mentioned above, we can also use PHP's built-in SimpleXMLElement class to convert XML into an array.

In the following code, we use PHP's built-in file_get_contents() function to obtain XML data from the specified URL:

$xmlstr = file_get_contents('http://localhost/webservice.php');

$xml = new SimpleXMLElement($xmlstr);
$json = json_encode($xml);
$array = json_decode($json, true);

print_r($array);
Copy after login

In the above code, we first use file_get_contents( ) function obtains XML data, and then uses PHP's built-in SimpleXMLElement class to convert the XML into a PHP object. Next, we use the json_encode() and json_decode() functions to convert the PHP object into an array, and finally use the print_r() function to print out the result.

The above code is very similar to the previous example, the only difference is that we use the SimpleXMLElement class to convert XML into objects. After conversion, we can use this data like an array.

Summary

This article introduces how to use PHP's built-in functions to convert the XML data returned by SOAP into an array. These techniques can make it easier for us to use the return value of the web service, thereby speeding up our development and integration. Whether using the simplexml_load_string() function or the SimpleXMLElement class, we can easily convert XML into a PHP array.

The above is the detailed content of How to convert xml returned by soap into an array in php. 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)

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 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.

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 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.

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.

See all articles