PHP创建与解析XML
随着 XML 不断的升温, PHP 提供了大量的用来专门处理 XML 的标准库 ( 类库 ) 来操控 XML 。例如 ,DOM XML 扩展的改写、 SimpleXML 扩展、 SOAP 扩展,还有PHP5.1 的 XMLReader 和XMLWrite 扩展等。
一. 使用 SimpleXML 操控 XML
要处理 XML 文件,有两种传统的处理思路: SAX 和 DOM 。 SAX 基于事件触发机制,对 XML 文件进行一次扫描,完成要进行的处理; DOM 则将整个 XML 文件构造为一棵 DOM树,通过对 DOM 树的遍历完成处理。这两种方法各有优缺点, SAX 的处理思路相对抽象,DOM 的处理过程相对烦琐,都不很适合新手的入门。PHP5 推出了一套新的 XML 处理函数,即 SimpleXML 。名如其实, SimpleXML 本身小巧精干,只提供了少量的几个方法函数,但用它处理起 XML 文件功能却非常强大,操作也非常的简单。
[php] view plaincopy
1. 创建 XML 文件
$ _ xml =
xml;
$ _sxe = new SimpleXMLElement( $ _xml ); // 创建对象解析 xml 字符串
$ _sxe ->asXML( 'test.xml' ); // 生成 XML 文件
2. 载入 XML 文件
$ _sxe = simplexml_load_file( "test.xml" ); // 载入 XML 文件
var_dump( $ _sxe ); // 输出相关信息
print_r( $ _sxe ); // 输出主要信息
Reflection::export( new ReflectionClass( $sxe )); // 用反射查看详情
3. 解析 XML 文件
$ _sxe = simplexml_load_file( "test.xml" ); // 载入 XML 文件
var_dump( $ _sxe ); // 输出相关信息
print_r( $ _sxe ); // 输出主要信息
Reflection::export( new ReflectionClass( $ _sxe )); // 用发射查看详情
echo $_ sxe ->asXML(); // 打印整个 XML
4. 读出 XML 数据
$_ sxe = simplexml_load_file( "test.xml" );
// 读取一级节点的值,比如 version 标签
echo $_ sxe ->version;
// 如果有多个,可以设置它的数字下标
echo $_ sxe ->version[ 2 ];
// 如果想要全部打印出来,可以用遍历
foreach ( $_ sxe ->version as $_version ) {
echo '[' . $_version . ']' ;
}
// 访问二级节点的 name
echo $_ sxe ->user[ 1 ]->name;
// 获取所有二级节点的 name 值
foreach ( $_ sxe ->user as $_user ) {
echo '[' . $_user ->name. ']' ;
}
// 获取二级节点的标签的属性
echo $_ sxe ->user[ 1 ]-> author ->attributes();
5. 使用 XPath 来获取节点
$_ sxe = simplexml_load_file( "test.xml" );
// 使用 XPath 获取节点信息www.2cto.com
$_version = $_ sxe ->xpath( '/root/version' );
echo $_version [ 1 ];
// 遍历 version
foreach ( $_version as $_v ) {
echo '[' . $_v . ']' ;
}
// 访问二级节点
$_user = $_ sxe ->xpath( '/root/user' );
echo $_use r [ 2 ]->name;
// 遍历二级节点
foreach ( $_user as $_u ) {
echo '[' . $_u ->name. ']' ;
}
// 访问属性
echo $_user [ 1 ]->author->attributes();
二. 使用 DOMDocument 操控 XML
很多情况下 , 手工生成标记要求从上到下生成文档 , 必须保证标签都是完整的 , 开始和结束标签。尽管借助于一些 PHP 函数或类可以有所改善,不过 PHP 还提供了一组更有帮助的内置对象和函数。文档对象模型( Document Object Model , DOM )提供了一个树状结构,能很容易创建和处理标签。
[php] view plaincopy
1. DOMDocument 解析 XML
// 创建一个 DOMDocument()
$_doc = new DOMDocument();
// 载入 xml
$_doc ->load( 'test.xml' );
// 取 version 标签
$_version = $_doc ->getElementsByTagName( 'version' );
echo $_version ->item( 2 )->nodeValue;
// 遍历 version 标签
foreach ( $_version as $v ) {
echo $v ->nodeValue;
}
2. DOMDocument 生成 XML
// 声明 xml
$_doc = new DOMDocument( '1.0' , 'utf-8' );
// 排版格式
$_doc ->formatOutput = true ;
// 创建一个主标签
$_root = $_doc ->createElement( 'root' );
// 创建一个一级标签 version
$_version = $_doc ->createElement( 'version' );
// 给 version 标签里赋值
$_versionTextNode = $_doc ->createTextNode( '1.0' );
// 将值放入 version 标签里
$_version ->appendChild( $_versionTextNode );
// 将一级标签 version 放入 root 里
$_root ->appendChild( $_version );
// 将主标签写入 xml
$_doc ->appendChild( $_root );
// 生成 xml
$_doc ->save( 'aaa.xml' );
摘自 geniusxiaoyu的专栏

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
