Home Backend Development PHP Tutorial Use SimpleXML to process XML files under PHP_PHP Tutorial

Use SimpleXML to process XML files under PHP_PHP Tutorial

Jul 21, 2016 pm 03:40 PM
php simplexml xml Down use deal with document have Introduction want

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


Copy code The code is as follows :


This is Title
Here is Content

< ;reply id='11'>reply 1
reply 2




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:
Copy codeThe 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321422.htmlTechArticle1 Introduction to SimpleXML To process XML files, there are two traditional processing ideas: SAX and DOM. Based on the event triggering mechanism, SAX scans the XML file once and completes the processing;...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles