search
HomeBackend DevelopmentPHP TutorialDetailed explanation of php operation xml_PHP tutorial

Detailed explanation of php operation xml_PHP tutorial

Jul 15, 2016 pm 01:21 PM
phpxmlbyexiststorageoperatedatadatabasedocumentyesFormatflowofStructuredDetailed explanation

XML is a popular semi-structured file format that stores data in a database-like format. In practical applications, some simple and low-security data are often stored in XML file format. The advantage of this is that on the one hand, it can improve reading efficiency by reducing interactive operations with the database, and on the other hand, it can effectively utilize the advantages of XML to reduce the difficulty of program writing.​

PHP provides a complete set of methods for reading XML files, making it easy to write XML-based scripts. This chapter will introduce the operation methods of PHP and XML, and give a brief introduction to several commonly used XML class libraries.
1 Introduction to XML
XML is the abbreviation of "eXtensible Markup Language" and is a markup language similar to HTML. But unlike HTML, XML is mainly used to describe data and store data, while HTML is mainly used to display data.
XML is a "meta tag" language that allows developers to create tag names according to their needs. For example, the following XML code can be used to describe a message.
Copy the code The code is as follows:
Welcome
Simon
Welcome to XML guestbook!!
Among them, the and tags mark this as a message. There is a title, author, and content in the message, which completely expresses a message message.
At the top of an XML file, is usually used to identify the beginning of XML data and XML data uses standard version information. When you access an XML file in a browser, you can see clearly structured XML data information, as shown in Figure 1.
XML is developing very rapidly. In recent years, many software developers have begun to adopt XML development standards for application development. Moreover, many emerging technologies are built on XML data. This means that XML will become as integral a part of Web technology as HTML.
2 Simple XML operations
In practical applications, the interaction between PHP and XML is widely used. SimpleXML component is a new simple addition to PHP5
A single XML operation component. Compared with traditional XML components, the use of SimpleXML components is very simple. This section will explain how to use
The SimpleXML component’s method of manipulating XML will be introduced in detail.
2.1 Create a SimpleXML object
SimpleXML object is a temporary variable used to temporarily store XML data. Operations on XML are completed by operating SimpleXML objects. The SimpleXML component provides two methods for creating SimpleXML objects. The first method is to use the simplexml_load_string function to read the XML data in a string variable to complete the creation. The syntax format is as follows.
simplexml_load_string(string data)
The data variable here is used to store XML data. The following code creates a SimpleXML object using the simplexml_load_string function
Copy the code The code is as follows:
$data =
production support
100001
Simon
24
1982-11-06
5000.00
1000.00
100002
Elaine
24
1982-01-01
6000.00
2000.00
testing center
110001
Helen
23
1983-07-21
5000.00
1000.00
XML;
$xml = simplexml_load_string($data); //Create SimpleXML object
print_r($xml); //Output XML
?>
In the above example, the $data variable stores a piece of XML data. The simplexml_load_string function converts the variable $data into a SimpleXML object. The structure of the object can be seen through the output of the print_r function, and the running results are as follows.
Copy the code The code is as follows:
SimpleXMLElement Object
(
[depart] => Array
(
[0] => SimpleXMLElement Object
(
[name] => production support
[employees] => SimpleXMLElement Object
( [employee] => Array (
[0] => SimpleXMLElement Object
( [serial_no] => 100001
[name] => Simon
[age] => 24
[birthday] => 1982-11-06
[salary] => 5000.00
[bonus] => 1000.00
)
[1] => SimpleXMLElement Object
( [serial_no] => 100002
[name] => Elaine
[age] => 24
[birthday] => 1982-01-01
[salary] => 6000.00
[bonus] => 2000.00
)
)
)
)
[1] => SimpleXMLElement Object
(
[name] => testing center
[employees] => SimpleXMLElement Object
(
[employee] => SimpleXMLElement Object
(
[serial_no] => 110001
[name] => Helen
[age] => 23
[birthday] => 1983-07-21
[salary] => 5000.00
[bonus] => 1000.00
)
)
)
)
)
As can be seen from the output results, the structure of the SimpleXML object is exactly the same as the format of the XML data.
The second method is to use the simplexml_load_flie function to read an XML file to complete the creation. The syntax format is as follows.
simplexml_load_file(string filename)
The filename variable here is the file name and path used to store the XML data file. The following code uses the simplexml_load_file function to create a SimpleXML object.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Create SimpleXML object
print_r($xml); //Output XML
?>
Among them, the data stored in example.xml is exactly the same as the $data above, and the running results are exactly the same as above.
The above two methods implement the same function, the difference lies in the different data sources of XML. If the XML data source is in a PHP script file, you need to use simplexml_load_string to create it. If the XML data source is in a separate XML file, you need to use simplexml_load_file to create it.
2.2 Read XML data in SimpleXML object
Previously we introduced the use of the print_r function to read data in a SimpleXML object, and its return result is similar to the structure of an array. Obviously, this display method is undesirable in practical applications. Here we will introduce several other methods of reading XML data in SimpleXML objects.
1. The var_dump function displays object details
The var_dump function can be used to display detailed information of SimpleXML objects. Compared with the print_r function, the var_dump function displays more complete information. Its syntax is as follows.
void var_dump(object1, object2 … )
The following code uses the var_dump function to output detailed information about the object in the above example.
Copy the code The code is as follows:
The running results are as follows.
Copy the code The code is as follows:
object(SimpleXMLElement)#1 (1) { ["depart"]=> array(2) { 
[0]=> 
object(SimpleXMLElement)#2 (2) { 
["name"]=> 
string(18) “production support” 
["employees"]=> 
object(SimpleXMLElement)#4 (1) { 
["employee"]=> 
array(2) { 
[0]=> 
object(SimpleXMLElement)#5 (6) { 
["serial_no"]=> 
string(6) “100001″ 
["name"]=> 
string(5) “Simon” 
["age"]=> 
string(2) “24″ 
["birthday"]=> 
string(10) “1982-11-06″ 
["salary"]=> 
string(7) “5000.00″ 
["bonus"]=> 
string(7) “1000.00″ 
[1]=> 
object(SimpleXMLElement)#6 (6) { 
["serial_no"]=> 
string(6) “100002″ 
["name"]=> 
string(6) “Elaine” 
["age"]=> 
string(2) “24″ 
["birthday"]=> 
string(10) “1982-01-01″ 
["salary"]=> 
string(7) “6000.00″ 
["bonus"]=> 
string(7) “2000.00″ 
[1]=> 
object(SimpleXMLElement)#3 (2) { 
["name"]=> 
string(14) “testing center” 
["employees"]=> 
object(SimpleXMLElement)#7 (1) { 
["employee"]=> 
object(SimpleXMLElement)#8 (6) { 
["serial_no"]=> 
string(6) “110001″ 
["name"]=> 
string(5) “Helen” 
["age"]=> 
string(2) “23″ 
["birthday"]=> 
string(10) “1983-07-21″ 
["salary"]=> 
string(7) “5000.00″ 
["bonus"]=> 
string(7) “1000.00″ 
}}}}} 
 
与前面 print_r输出的结果相比较,var_dump函数的输出结果的结构更为严谨,并且将对象中的每一个属性的数据类型均作出分析。在实际应用中,var_dump函数往往用于程序调试时的对象检测。 
2.读取 XML数据中的标签 
与操作数组类型的变量类似,读取 XML也可以通过类似的方法来完成。例如,如果需要读取上面 XML数据中每一个“ depart”标签下的“name”属性,可以通过使用 foreach函数来完成,如以下代码 
所示。 
复制代码 代码如下:
depart as $a) 
echo “$a->name
”; 
?> 
 
运行结果如下所示。 
production support 
testing center 
//读取 XML文件 //循环读取 XML数据中的每一个 depart标签 
//输出其中的 name属性 
也可以使用方括号“ []”来直接读取 XML数据中指定的标签。以下代码输出了上面 XML数据中的第一个“depart”标签的“name”属性。 
复制代码 代码如下:
$xml = simplexml_load_file('example.xml'); //读取 XML文件 
echo $xml->depart->name[0]; //输出节点 
?> 
 
运行结果如下所示。 
production support 
对于一个标签下的所有子标签,SimpleXML组件提供了 children方法进行读取。例如,对于上面的 XML数据中的“ depart”标签,其下包括两个子标签:“ name”和“employees”。以下代码实现了对第一个“depart”标签下的子标签的读取。 
复制代码 代码如下:
$xml = simplexml_load_file('example.xml');
foreach ($xml->depart->children() as $depart) //Loop to read the sub-tags under the depart tag
{
var_dump($depart); //Output the XML data of the tag
}
?>
The running results are as follows.
Copy the code The code is as follows:
object(SimpleXMLElement)#3 (1) {
[0]=>
string(18) “production support”
}
object(SimpleXMLElement)#5 (1) {
["employee"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#3 (6) {
["serial_no"]=>
string(6) “100001″
["name"]=>
string(5) “Simon”
["age"]=>
string(2) “24″
["birthday"]=>
string(10) “1982-11-06″
["salary"]=>
string(7) “5000.00″
["bonus"]=>
string(7) “1000.00″
}
[1]=>
object(SimpleXMLElement)#6 (6) {
["serial_no"]=>
string(6) “100002″
["name"]=>
string(6) “Elaine”
["age"]=>
string(2) “24″
["birthday"]=>
string(10) “1982-01-01″
["salary"]=>
string(7) “6000.00″
["bonus"]=>
string(7) “2000.00″
}
}
}
It can be seen that after using the children method, all child tags are treated as a new XML file.
3. Query based on XML data path
SimpleXML component provides a query method based on XML data path. The XML data path is all the tags that pass from the root of XML to a certain tag. This path uses slashes "/" to separate tag names. For example, for the above XML data, if you want to query the values ​​​​in all tags "name", starting from the root and going through the departs, department, employees and employee tags, the path is
is "/departs/depart/employees/employee/name". The SimpleXML component uses the xpath method to parse paths, and its syntax format is as follows.
xpath(string path)
The path is the path. This method returns an array containing all tag values ​​to be queried. The following code queries all name tags in the above XML data.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML file
$result = $xml->xpath('/departs/depart/employees/employee/name'); //Define node
var_dump($result); //Output node
?>
The running results are as follows.
Copy the code The code is as follows:
array(3) {
[0]=> object(SimpleXMLElement)#2 (1) {
[0]=> string(5) “Simon”
}
[1]=> object(SimpleXMLElement)#3 (1) {
[0]=> string(6) “Elaine”
}
[2]=> object(SimpleXMLElement)#4 (1) {
[0]=> string(5) “Helen”
}
}
It can be seen that all name tags have been queried.
2.3 Modification of XML data
The modification of XML data is similar to the method of reading tags in XML data. That is, by directly modifying the value of the tag in the SimpleXML object. The following code implements the modification of the "name" sub-tag of the first "depart" tag in the XML data above.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML
$xml->depart->name[0] = “Human Resource”; //Modify node
?>
After modification, it will not have any impact on the XML file. However, in the program, the modified value will be used for reading the SimpleXML object.
2.4 Standardized XML data
SimpleXML also provides a way to standardize XML data asXML. The asXML method can effectively rearrange the content in the SimpleXML object according to the XML 1.0 standard and return it as a string data type. The following code implements the standardization of the above XML data.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML data
echo $xml->asXML(); //Standardized XML data
?>
2.5 Storage of XML data
The method of storing XML data in a SimpleXML object into an XML file is very simple, that is, outputting the return result of the asXML method to a file. The following code first modifies the depart name in the XML file, and then outputs the modified XML data to another XML file.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML data
$newxml = $xml->asXML(); //Standardized XML data
$fp = fopen(”newxml.xml”, “w”); //Open the file to write XML data
fwrite($fp, $newxml); //Write XML data
fclose($fp); //Close the file
?>
After the code is run, you can see that the XML data in the newxml.xml file is as follows.
It can be seen that the modifications to the XML file have been saved in the output file.
3 Dynamic creation of XML documents
In practical applications, it is sometimes necessary to dynamically generate XML documents. The SimpleXML component introduced earlier does not provide a method for creating XML documents. Therefore, if you need to dynamically create an XML document, you often use DOM components to create it. DOM is the abbreviation of Document Object Model. The DOM component provides a tree parsing mode for XML documents. The following code creates an XML document using DOM components.
Copy the code The code is as follows:
//Create a new DOM document
$dom = new DomDocument();
//Create the departs label at the root node
$departs = $dom->createElement('departs');
$dom->appendChild($departs);
//Create the depart sub-tag under the departs tag
$depart = $dom->createElement('depart');
$departs->appendChild($depart);
//Create employees sub-tag under the depart tag
$employees = $dom->createElement('employees');
$depart->appendChild($employees);
//Create employee sub-tag under employees tag
$employee = $dom->createElement('employee');
$employees->appendChild($employee);
//Create serial_no sub-tag under employee tag
$serial_no = $dom->createElement('serial_no');
$employee->appendChild($serial_no);
//Add value node 100001 for serial_no tag
$serial_no_value = $dom->createTextNode('100001′);
$serial_no->appendChild($serial_no_value);
//Output XML data
echo $dom->saveXML();
?>
The output results are shown below.
100001
In addition to being used to dynamically create XML documents, the DOM component can also be used to read XML files. The following code implements the front
Reading of XML files.
Copy the code The code is as follows:
$dom = new DomDocument(); //Create DOM object
$dom->load('example.xml'); //Read XML file
$root = $dom->documentElement; //Get the root of XML data
read_child($root); //Call the read_child function to read the root object
function read_child($node)
{
$children = $node->childNodes; //Get all child nodes of $node
foreach($children as $e) //Loop to read each child node
{
if($e->nodeType == XML_TEXT_NODE) ​​//If the child node is text type, output
{
echo $e->nodeValue.”
”;
}
else if($e->nodeType == XML_ELEMENT_NODE) ​​//If the child node is a node object, call the function processing
{
read_child($e);
}
}
}
?>
The running results are as follows.
Copy the code The code is as follows:
Quote
production support
100001
Simon
24
1982-11-06
5000.00
1000.00
100002
Elaine
24
1982-01-01
6000.00
2000.00
testing center
110001
Helen
23
1983-07-21
5000.00
1000.00
The above example uses a recursive method to process XML data and realizes the function of outputting all text tags in XML data.
4 XML application examples - Guestbook
The basic operations of XML have been introduced before. This section will take designing an XML guestbook as an example to explain in detail how to realize the interaction between PHP and XML data in practical applications.
4.1 XML file structure design
XML files are used to store XML data, which are the messages in the guestbook. Here, for each message, the XML data mainly includes three contents: message title, message author's name, and message content. Therefore, the format of the XML file is designed as follows.
Copy the code The code is as follows:
Here is the title of the message
This is the commenter
Here is the content of the message
4.2 Writing the submission page
The message submission page consists of two pages. One is an HTML file for a form that allows visitors to write messages, and the other is a PHP script used to process visitor input. The HTML code for the form is shown below.
Copy the code The code is as follows:
Post a new comment

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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.