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 and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

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.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

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