用PHP编写和读取XML的几种方式
发布时间:2023-11-18 22:30:27
标签:编写XML,读取XML
一.使用DOM生成和读取XML文件
实例一:
<?php
//Creates XML string and XML document using the DOM
$dom = new DomDocument('1.0');
//add root - <books>
$books = $dom->appendChild($dom->createElement_x_x ('books'));
//add <book> element to <books>
$book = $books->appendChild($dom->createElement_x_x ('book'));
//add <title> element to <book>
$title = $book->appendChild($dom->createElement_x_x ('title'));
//add <title> text node element to <title>
$title->appendChild($dom->createTextNode('Great American Novel'));
//generate xml
$dom->formatOutput = true; // set the formatOutput attribute of domDocument to true
//save XML as string or file
$test1 = $dom->saveXML(); // put string in test1
$dom -> save('test1.xml'); // save as file
?>
实例二:
$aa = "111";
$xmlstr = <<<XML
<?xml version='1.0'?>
<document>
<title>{$aa}</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that's the answer -- but what's the question?
</body>
</document>
XML;
$dom = new domDocument;
$dom->loadXML($xmlstr);
$test1 = $dom->saveXML();
$dom->save('test1.xml');
实例三:
test1.xml:
<?xml version="1.0"?>
<books>
<book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
example.php:
$doc = new DOMDocument();
$doc->load('test1.xml');
$books = $doc->getElementsByTagName("book");
foreach($books as $book){
$authors = $book->getElementsByTagName("author");
$author = $authors->item(0)->nodeValue;
$publishers = $book->getElementsByTagName( "publisher" );
$publisher = $publishers->item(0)->nodeValue;
$titles = $book->getElementsByTagName( "title" );
$title = $titles->item(0)->nodeValue;
echo "$title - $author - $publisher\n";
}
二.使用simple生成和读取xml文件
实例一:
<?
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<books>
<book>
<title>Great American Novel</title>
<characters>
<character>
<name>Cliff</name>
<desc>really great guy</desc>
</character>
<character>
<name>Lovely Woman</name>
<desc>matchless beauty</desc>
</character>
<character>
<name>Loyal Dog</name>
<desc>sleepy</desc>
</character>
</characters>
<plot>
Cliff meets Lovely Woman. Loyal Dog sleeps, but wakes up to bark
at mailman.
</plot>
<success type='bestseller'>4</success>
<success type='bookclubs'>9</success>
</book>
</books>
XML;
//提取节点内容
$xml = new SimpleXMLElement($xmlstr);
foreach ($xml->book[0]->success as $success) {
switch((string) $success['type']) { // Get attributes as element indices
case 'bestseller':
echo $success. ' months on bestseller list<br>';
break;
case 'bookclubs':
echo $success. ' bookclub listings';
break;
}
}
//修改文本节点内容
$xml = new SimpleXMLElement($xmlstr);
$xml->book[0]->characters->character[0]->name = 'Big Cliff';
echo $xml->asXML();
//添加子元素的文本节点
$xml = new SimpleXMLElement($xmlstr);
$character = $xml->book[0]->characters->addChild('character');
$character->addChild('name', 'Yellow Cat');
$character->addChild('desc', 'aloof');
$success = $xml->book[0]->addChild('success', '2');
$success->addAttribute('type', 'reprints');
echo $xml->asXML();
?>
实例二:
if (file_exists('test1.xml')) { //读取xml文件
$xml = simplexml_load_file('test1.xml');
var_dump(xml);
} else {
exit('Failed to open test1.xml.');
}
三.DOM和simple互操作
DOM导入simpleXML:
<?php
$sxe = simplexml_load_string('<books><book><title>Great American
Novel</title></book></books>');
if ($sxe === false) {
echo 'Error while parsing the document';
exit;
}
$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
echo 'Error while converting XML';
exit;
}
$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);
$test2 = $dom->saveXML(); // put string in test2
$dom -> save('test2.xml'); // save as file
?>
simpleXML导入DOM:
<?php
$dom = new domDocument;
$dom->loadXML('<books><book><title>Great American
Novel</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$s = simplexml_import_dom($dom);
echo $s->book[0]->title; // Great American Novel
?>


猜你喜欢
- 项目开发中hadoop一直装在虚拟机上,最近要迁移到服务器上。记录下迁移过程。一、为虚拟机添加一块新的硬盘虚拟机的初始硬盘只有30G,容不开
- 这是一个很长的故事,嫌长的直接看最后的结论事情经过上周接了个需求,写了个小工具给客户,他要求打包成exe文件,这当然不是什么难事。因为除了写
- 在本人看来,HTML 5是一个妥协方案,虽不激进,但更能推动技术的继续进步。没有命名空间,元素也不要求闭合(当然这并不是优点),浏览器也可以
- 本文实例讲述了Python定时任务sched模块用法。分享给大家供大家参考,具体如下:通过sched模块可以实现通过自定义时间,自定义函数,
- 最近工作中慢慢开始用python协程相关的东西,所以用到了一些相关模块,如aiohttp, aiomysql, aioredis等,用的过程
- java连接sqlserver2008数据库代码如下所示:public class SqlServer { public static vo
- python中向上取整可以用ceil函数,ceil函数是在math模块下的一个函数。向上取整需要用到 math 模块中的 ceil() 方法
- 本文实例讲述了Python实现购物评论文本情感分析操作。分享给大家供大家参考,具体如下:昨晚上发现了snownlp这个库,很开心。先说说我开
- 值得学习的地方:1.选择合法索引的方式2.数组转图像显示import numpy as npfrom PIL import Image#in
- 有三种主要的错误类型: 1.编译错误: 这种错误出现一般都是代码的语法问题。因为编译错误而导致辞ASP停止运行。 2.运行错误: 这个错误是
- 一个快速的REST例子首先来看些基本知识。如果没有服务API,Neo4j就不能支持其他语言。该接口提供一组基于JSON消息格式的
- 哲学上有种说法,“运动是绝对的,静止是相对的”。我们在编写各样的效果时,时常会碰到动画。下面的章,将讨论动画的原理以及实现。动画,简而言之就
- 一般情况下会有几种情况需要你把数据库设为只读: 1. Insert,Update,Delete 触发器 2. Check 约束 和 Dele
- 如下所示:import tensorflow as tfsess = tf.Session(config=tf.ConfigProto(lo
- 本文以一段简单的监听鼠标、键盘事件的程序,实现获取用户的输入(比如登录某些网站的账号、密码)的功能。经测试,对于一台“裸奔”的电脑,完全能获
- PyGame是一个Python的库,能够让你更容易的写出一个游戏。它提供的功能包括图片处理和声音重放的功能,并且它们能很容易的整合进你的游戏
- 首先简单介绍一下什么叫MySQL;数据库简而言之就是存储数据的仓库,为了方便数据的存储和管理,它将数据按照特定的规律存储在磁盘上。是为了实现
- 本文实例为大家分享了Python基于OpenCV实现人脸检测,并保存的具体代码,供大家参考,具体内容如下安装opencv如果安装了pip的话
- 学用python也有3个多月了,用得最多的还是各类爬虫脚本:写过抓代理本机验证的脚本,写过在discuz论坛中自动登录自动发贴的脚本,写过自
- 铺垫在大量的实践中,似乎我们总是通过类似的方式来使用异步编程:监听事件事件发生执行对应的回调函数回调完成(可能产生新的事件添加进监听队列)回