PHP中DOMDocument生成与解析XML格式数据
DOMDocument这个功能是我们php中自带的一个功能,下面我来介绍利用DOMDocument生成xml文档,并且也介绍DOMDocument解析xml文件的方法,有需要的朋友可参考.
数组实例代码如下:
<?php $arr[] = array( 'name' => $row['name'], 'sex' => $row['sex'], 'age' => $row['age'] ); ?>
Copy after login
生成php,代码如下:
<?php $doc = new DOMDocument('1.0', 'utf-8'); // 声明版本和编码 $doc->formatOutput = true; $r = $doc->createElement("root"); $doc->appendChild($r); foreach ($arr as $dat) { $b = $doc->createElement("data"); $name = $doc->createElement("name"); $name->appendChild($doc->createTextNode($dat['name'])); $b->appendChild($name); $sex = $doc->createElement("sex"); $sex->appendChild($doc->createTextNode($dat['sex'])); $b->appendChild($sex); $age = $doc->createElement("age"); $age->appendChild($doc->createTextNode($dat['age'])); $b->appendChild($age); $r->appendChild($b); } echo $doc->saveXML(); ?>
Copy after login
这样就生成了一个xml文件了.
解析xml文件也是非常的简单了,代码如下:
<?php header("Content-type:text/html; Charset=utf-8"); $url = "createXML.php"; $reader = new XMLReader(); //实例化XMLReader $reader->open($url); //获取xml $i = 1; while ($reader->read()) { if ($reader->nodeType == XMLReader::TEXT) { //判断node类型 $m = $i % 3; if ($m == 1) $name = $reader->value; //读取node值 if ($m == 2) $sex = $reader->value; if ($m == 0) { $age = $reader->value; $arr[] = array( 'name' => $name, 'sex' => $sex, 'age' => $age ); } $i++; } } //print_r($arr); ?>
Copy after login
文章地址:
转载随意^^请带上本文地址!
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
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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
4 weeks ago
By DDD
R.E.P.O. Save File Location: Where Is It & How to Protect It?
4 weeks ago
By DDD
Two Point Museum: All Exhibits And Where To Find Them
1 months ago
By 尊渡假赌尊渡假赌尊渡假赌

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)
