search
HomeBackend DevelopmentPHP TutorialPHP creates and parses XML 1 (36)

1. Use SimpleXML to manipulate XML

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; 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 ideas are relatively abstract, and DOM's processing process is relatively cumbersome, making them neither very suitable for beginners. 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 in processing XML files and the operation is also very simple.

 1.Create XML file

$_xml =xml
<?xml version=<span>"<span>1.0</span><span>"</span> encoding=<span>"</span><span>utf-8</span><span>"</span>?>
<root>
<version><span>1.0</span></version>
<info>xml解析测试</info>
<user>
<name>张三</name>
<url>http:<span>//</span><span>www.ss.com</span></url><author sex="<span">"<span>男</span><span>"</span>>张三</author>
</user>
<user>
<name>宿舍</name>
<url>http:<span>//</span><span>www.ss.com</span></url><author sex="<span">"<span>女</span><span>"</span>>谁谁谁</author>
</user>
<user>
<name>电驴</name>
<url>http:<span>//</span><span>www.ss.com</span></url><author sex="<span">"<span>男</span><span>"</span>>姓黄的</author>
</user>
</root><span>xml;
$_sxe</span>= <span>new</span> SimpleXMLElement($_xml); <span>//</span><span>创建对象解析xml字符串</span>$_sxe->asXML(<span>'</span><span>test.xml</span><span>'</span>); <span>//</span><span>生成XML文件</span>

 2.Load XML file

$_sxe= simplexml_load_file(<span>"</span><span>test.xml</span><span>"</span>); <span>//</span><span>载入XML文件</span>var_dump($_sxe); <span>//</span><span>输出相关信息</span>print_r($_sxe); <span>//</span><span>输出主要信息</span>Reflection::export(<span>new</span> ReflectionClass($sxe)); <span>//</span><span>用反射查看详情</span>

 3.Parse XML file

$_sxe= simplexml_load_file(<span>"</span><span>test.xml</span><span>"</span>); <span>//</span><span>载入XML文件</span>var_dump($_sxe); <span>//</span><span>输出相关信息</span>print_r($_sxe); <span>//</span><span>输出主要信息</span>Reflection::export(<span>new</span> ReflectionClass($_sxe)); <span>//</span><span>用发射查看详情</span>echo $_sxe->asXML();<span>//</span><span>打印整个XML</span>

 4.Read XML data

$_sxe= simplexml_load_file(<span>"</span><span>test.xml</span><span>"</span><span>);
</span><span>//</span><span>读取一级节点的值,比如version标签</span>echo $_sxe-><span>version;
</span><span>//</span><span>如果有多个,可以设置它的数字下标</span>echo $_sxe->version[<span>2</span><span>];
</span><span>//</span><span>如果想要全部打印出来,可以用遍历</span><span>foreach</span> ($_sxe->version <span>as</span><span> $_version) {
echo </span><span>'</span><span>[</span><span>'</span>.$_version.<span>'</span><span>]</span><span>'</span><span>;
}
</span><span>//</span><span>访问二级节点的name</span>echo $_sxe->user[<span>1</span>]-><span>name;
</span><span>//</span><span>获取所有二级节点的name值</span><span>foreach</span> ($_sxe->user <span>as</span><span> $_user) {
echo </span><span>'</span><span>[</span><span>'</span>.$_user->name.<span>'</span><span>]</span><span>'</span><span>;
}
</span><span>//</span><span>获取二级节点的标签的属性</span>echo $_sxe->user[<span>1</span>]->author->attributes();

 5.Use XPath to get Node

$_sxe= simplexml_load_file(<span>"</span><span>test.xml</span><span>"</span><span>);
</span><span>//</span><span>使用XPath获取节点信息</span>$_version = $_sxe->xpath(<span>'</span><span>/root/version</span><span>'</span><span>);
echo $_version[</span><span>1</span><span>];
</span><span>//</span><span>遍历version</span><span>foreach</span> ($_version <span>as</span><span> $_v) {
echo </span><span>'</span><span>[</span><span>'</span>.$_v.<span>'</span><span>]</span><span>'</span><span>;
}
</span><span>//</span><span>访问二级节点</span>$_user = $_sxe->xpath(<span>'</span><span>/root/user</span><span>'</span><span>);
echo $_user[</span><span>2</span>]-><span>name;
</span><span>//</span><span>遍历二级节点</span><span>foreach</span> ($_user <span>as</span><span> $_u) {
echo </span><span>'</span><span>[</span><span>'</span>.$_u->name.<span>'</span><span>]</span><span>'</span><span>;
}
</span><span>//</span><span>访问属性</span>echo $_user[<span>1</span>]->author->attributes();

two. Using DOMDocument to manipulate XML

In many cases, manual generation of tags requires generating documents from top to bottom. It is necessary to ensure that the tags are complete, starting and ending tags. Although some improvements can be made with the help of some PHP functions or classes, PHP also provides a more helpful set of built-in objects and functions. The Document Object Model (DOM) provides a tree structure that makes it easy to create and process tags.

 1.DOMDocument parses XML

<span>//</span><span>创建一个DOMDocument()</span>$_doc = <span>new</span><span> DOMDocument();
</span><span>//</span><span>载入xml</span>$_doc->load(<span>'</span><span>test.xml</span><span>'</span><span>);
</span><span>//</span><span>取version标签</span>$_version = $_doc->getElementsByTagName(<span>'</span><span>version</span><span>'</span><span>);
echo $_version</span>->item(<span>2</span>)-><span>nodeValue;
</span><span>//</span><span>遍历version标签</span><span>foreach</span> ($_version <span>as</span><span> $v) {
echo $v</span>-><span>nodeValue;
}</span>

 2.DOMDocument generates XML

<span>//</span><span>声明xml</span>$_doc = <span>new</span> DOMDocument(<span>'</span><span>1.0</span><span>'</span>,<span>'</span><span>utf-8</span><span>'</span><span>);
</span><span>//</span><span>排版格式</span>$_doc->formatOutput = <span>true</span><span>;
</span><span>//</span><span>创建一个主标签</span>$_root = $_doc->createElement(<span>'</span><span>root</span><span>'</span><span>);
</span><span>//</span><span>创建一个一级标签version</span>$_version = $_doc->createElement(<span>'</span><span>version</span><span>'</span><span>);
</span><span>//</span><span>给version标签里赋值</span>$_versionTextNode = $_doc->createTextNode(<span>'</span><span>1.0</span><span>'</span><span>);
</span><span>//</span><span>将值放入version标签里</span>$_version-><span>appendChild($_versionTextNode);
</span><span>//</span><span>将一级标签version放入root里</span>$_root-><span>appendChild($_version);
</span><span>//</span><span>将主标签写入xml</span>$_doc-><span>appendChild($_root);
</span><span>//</span><span>生成xml</span>$_doc->save(<span>'</span><span>aaa.xml</span><span>'</span>);

The above introduces PHP creation and parsing XML 1 (36), including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.