当前位置: 网学 > 编程文档 > PHP > 正文

用PHP编写和读取XML的几种方式

来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: 用户投稿 来源: 网络 发布时间: 13/06/18

网学网为广大网友收集整理了,用PHP编写和读取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>
&

网学推荐

免费论文

原创论文

浏览:
设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
湘ICP备09003080号