search
HomeBackend DevelopmentPHP ProblemHow to convert XML document to array in PHP

In the PHP development process, XML processing is a very common operation, and PHP provides many functions and class libraries for XML processing. Among them, the function of converting XML documents into PHP arrays is a very important operation, because it can easily use XML data for subsequent operations and logical analysis. This article will discuss some commonly used functions in PHP for converting XML documents into PHP arrays.

1. simplexml_load_string()

simplexml_load_string() is a commonly used function in PHP, which can convert XML documents into simple XML objects in PHP. This function receives an XML document as a string and creates a simple XML object by parsing the document. The following is a simple example:

$xml_string = "<students><student><name>Tom</name><age>18</age></student></students>";
$xml_object = simplexml_load_string($xml_string);
print_r($xml_object);

The above code will output the following results:

SimpleXMLElement Object
(
    [student] => SimpleXMLElement Object
        (
            [name] => Tom
            [age] => 18
        )
)

In the above example, we use an XML string as a parameter of the simplexml_load_string() function, and Assign the returned object to the $xml_object variable. We found that the value of $xml_object is a SimpleXMLElement object, which contains all the data in the XML document.

It should be noted that the simplexml_load_string() function is usually used for simple XML document processing. If your XML document is more complex, it is recommended to use other XML processing functions and class libraries.

2. simplexml_load_file()

The simplexml_load_file() function is very similar to the simplexml_load_string() function. The only difference is that the former parses the XML document from the PHP file system. The following is a simple example:

$xml_file = "students.xml";
$xml_object = simplexml_load_file($xml_file);
print_r($xml_object);

The above code will output the following results:

SimpleXMLElement Object
(
    [student] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [name] => Tom
                    [age] => 18
                )
        )
)

In the above example, we use the simplexml_load_file() function to parse an XML file into a SimpleXMLElement object And assign it to the $xml_object variable. This function facilitates parsing XML files from the file system, but you also need to be aware of the complexity of XML files.

3. xml_parse_into_struct()

xml_parse_into_struct() function is a very commonly used function in PHP, which can parse XML documents into PHP arrays. Different from the simplexml_load_string() function and simplexml_load_file() function, the xml_parse_into_struct() function returns a two-dimensional array that contains all elements and attributes in the XML document. The following is a simple example:

$xml_string = "<students><student><name>Tom</name><age>18</age></student></students>";
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xml_string, $xml_array);
xml_parser_free($xml_parser);
print_r($xml_array);

The above code will output the following results:

Array
(
    [0] => Array
        (
            [tag] => students
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => student
            [type] => open
            [level] => 2
        )

    [2] => Array
        (
            [tag] => name
            [type] => complete
            [level] => 3
            [value] => Tom
        )

    [3] => Array
        (
            [tag] => age
            [type] => complete
            [level] => 3
            [value] => 18
        )

    [4] => Array
        (
            [tag] => student
            [type] => close
            [level] => 2
        )

    [5] => Array
        (
            [tag] => students
            [type] => close
            [level] => 1
        )
)

In the above example, we use the xml_parser_create() function to create an XML parser, and then use The xml_parse_into_struct() function parses an XML string into a PHP array and assigns it to the $xml_array variable. Finally, we use the print_r() function to output the value of the $xml_array array.

It should be noted that the xml_parse_into_struct() function is only suitable for parsing small XML documents. For large and complex XML documents, it is recommended to use other XML parsing functions or libraries.

4. DOMDocument class

The DOMDocument class is a very commonly used and powerful XML parser in PHP. It can parse XML documents into DOM objects and provides a set of APIs to access and modify the nodes and properties of this object. The following is a simple example:

$xml_string = "<students><student><name>Tom</name><age>18</age></student></students>";
$dom_document = new DOMDocument();
$dom_document->loadXML($xml_string);
$students = $dom_document->getElementsByTagName('student');
foreach ($students as $student) {
    $name = $student->getElementsByTagName('name')->item(0)->nodeValue;
    $age = $student->getElementsByTagName('age')->item(0)->nodeValue;
    echo "Name: $name, Age: $age";
}

The above code will output the following results:

Name: Tom, Age: 18

In the above example, we use the DOMDocument class to parse the XML string into a DOM object, and use The getElementsByTagName() function selects the student node. Finally, we use the nodeValue property to get the value of the node and output it to the screen.

It should be noted that the DOMDocument class provides a wealth of methods and attributes for operating and modifying XML documents, making it the best choice for XML parsing and processing.

Summary

In this article, we have introduced in detail some common functions and class libraries in PHP for converting XML documents into PHP arrays. These functions and class libraries can easily use XML data for subsequent operations and logical analysis. In actual use, depending on the complexity of the XML document and the usage scenarios, we can choose different functions and class libraries to complete our XML processing tasks.

The above is the detailed content of How to convert XML document 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

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

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