Use SimpleXML to process XML files under PHP_PHP Tutorial
1 Introduction to SimpleXML
To process XML files, there are two traditional processing ideas: SAX and DOM. SAX is based on an event triggering mechanism.
scans the XML file once to complete the processing; DOM constructs the entire XML file into a DOM
tree, and completes the processing by traversing the DOM tree. Both methods have their own advantages and disadvantages. SAX's processing idea is relatively abstract, and
DOM's processing process is relatively cumbersome, making them neither very suitable for beginners to get started.
PHP5 introduces a new set of XML processing functions, namely SimpleXML. As the name suggests, SimpleXML itself is small and compact, and only provides a few methods and functions. However, it is very powerful for processing XML files and the operation is very simple.
First of all, it provides simple functions to directly construct
SimpleXMLElement objects from XML documents, strings, or DOM objects; secondly, SimpleXMLElement provides simple methods to construct attributes and subsections
, and XPath operations; however, the simplest thing about SimpleXML is that it provides methods for node operations using standard object attributes and
object iterators. This processing idea makes it possible to use PHP to process XML documents. A huge
simplification.
2 SimpleXML Getting Started Example
Below we use some small code snippets to understand a little about the power and simplicity of SimpleXML. For the convenience of example, We use a Messages.xml file, which contains this XML code:
Messages.xml
< ;reply id='11'>reply 1
This is an XML document that saves message information. Each message includes attribute id, sub-nodes title, content, time
and several reply messages to it. Each reply includes attribute id and reply. content.
The process and method of using SimpleXML to process and output the content of this XML document are as follows.
(1) Construct SimpleXMLElement object
Code snippet
$xml = simplexml_load_file('Messages.xml');
If this xml has been read into a string $messages , you can use the following statement:
Code snippet
$xml = simplexml_load_string('Messages.xml');
(2) Output the title of message 1
Code snippet
//can be used Access child nodes through attributes, and you can directly get the content of the node through the node's label name
echo $xml->msg->title;
(3) Output the first reply message of message 1
Code snippet
//Multiple nodes with the same name at the same level automatically become arrays, and their contents can be accessed through index subscripts
echo $xml->msg->reply[0];
(4 ) Output the id of the message
Code snippet
//The attributes and values of the node are encapsulated into the keys and values of the associative array
echo $xml->msg['id'];
(5 ) Output the id of the second reply
Code snippet
//Become a two-dimensional array, the first dimension represents the node, and the second dimension represents the attribute
echo $xml->msg->reply[1 ][ 'id'];
(6) Output the ids of all replies in sequence
Code snippets
//Use foreach to traverse the node with the same name
foreach ($xml->msg-> reply as $reply){
echo $reply['id'];
}
(7) Use XPath to retrieve all reply information
Code snippet
//xpath method to directly retrieve the location (// represents any depth)
foreach ($xml->xpath('//reply') as $reply){
echo $reply.'
';
}
(8) Traverse all child nodes of message 1
Code snippet
//children method to get all child nodes
foreach ($xml->msg->children() as $field ){
echo $field.'
';
}
(9) Reset the publishing time of message 1
Code snippet
//Set attributes directly
$ xml->msg->time = '2008-03-21 00:53:12';
(10) Set the id attribute of reply 2
Code snippet
//Set the value of the management array
$xml->msg->reply[1]['id'] = '222';
(11) Add a field describing the message author
Code snippet
// Directly set the attribute
$xml->msg->author = 'zhangsan';
(12) Save the author of the message as an attribute
Code snippet
//Set the key of the associative array
$xml->msg['author'] = 'zhangsan';
(13) Resave the object to the file
Code snippet
//Save
$xml->asXML( 'MessagesNew.xml');
You should be able to see how simple SimpleXML is!
3 Example: Data interaction between XML files and databases
A relatively complete example is provided below to query the message information from the MySQL database and save it as an
XML file as shown in the above example. . Message information and reply information are stored independently in two tables. Using the MySQL function package
can be very simply implemented as follows:
The code is as follows:
//cong work atWed Mar 20 19:59:04 CST 2008
//Save data from MySQL database to XML file
//Can be used Construct the initial SimpleXMLElement object in the following ways
//1. Construct from the DOM object
//$dom = new DOMDocument();
//$dom->loadXML("
//$xml = simplexml_import_dom($dom);
//2. Construct from an xml file containing only the root tag
//$xml = simplexml_load_file( 'messages.xml');
//3. Write the root tag string structure directly
//$xml = simplexml_load_string("
//4 , use the constructor of the SimpleXMLElement class to construct
$xml = new SimpleXMLElement('
//Connect to the database
mysql_connect('localhost','root', 'root');
mysql_select_db('test');
mysql_query('set names utf8');
//Query messages
$rs = mysql_query("select * from messages");
$i = 0; //Used as array index subscript for multiple messages
while($row = mysql_fetch_assoc($rs)){
$xml->message[$i] = ' '; //… … … … … … … … … … … … … … ①
$xml->message[$i]['id'] = $row['id'];
$xml- >message[$i]->title = $row['title'];
$xml->message[$i]->content = $row['content'];
$ xml->message[$i]->time = $row['time'];
//Query its related reply information based on message id
$rsReply = mysql_query("select * from replies where mid={$row['id']}");
$j = 0; //Index subscript for multiple replies
while($rowReply = mysql_fetch_assoc($rsReply)){
$xml->message[$i]->reply[$j] = $rowReply['reply'];
$xml->message[$i]->reply[$j] ['id'] = $rowReply['id'];
$j++;
}
$i++;
}
$xml->asXML('messages.xml') ;
?>
The only thing worth mentioning about the above code is the line marked ①. When we want to
add a new node or attribute to a SimpleXML object, we must ensure that its parent node exists, otherwise a fatal error will be reported. The prompt message is:
Objects used as arrays in post/ pre increment/decrement must return values by reference. I hope everyone
will not be confused by this unintelligible reminder. I believe that readers can write a code from XML file to MySQL by understanding the above code.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


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

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),

WebStorm Mac version
Useful JavaScript development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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.