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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP: An Introduction to the Server-Side Scripting Language PHP: An Introduction to the Server-Side Scripting Language Apr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

C   and XML: Exploring the Relationship and Support C and XML: Exploring the Relationship and Support Apr 21, 2025 am 12:02 AM

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

See all articles