search
HomeBackend DevelopmentPHP TutorialUse 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
phpsimplexmlxmlDownusedeal withdocumenthaveIntroductionwant

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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool