WEB开发网
开发学院WEB开发PHP PHP读写XML文件技巧 阅读

PHP读写XML文件技巧

 2012-12-04 20:42:27 来源:WEB开发网   
核心提示:访问MySql数据库 高级篇 AJAX技术","link"=>"http://blog.csdn.net/morewindows/article/details/7086524"),);$dom = new DOMDocument('1.0', &
访问MySql数据库 高级篇 AJAX技术",
"link"=>"http://blog.csdn.net/morewindows/article/details/7086524"
),
);
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$rootelement = $dom->createElement("MoreWindows");
foreach ($article_array as $key=>$value)
{
$article = $dom->createElement("article", $key);
$title = $dom->createElement("title", $value['title']);
$link = $dom->createElement("link", $value['link']);
$article->appendChild($title);
$article->appendChild($link);
$rootelement->appendChild($article);
}
$dom->appendChild($rootelement);
$filename = "D:\\test.xml";
echo 'XML文件大小' . $dom->save($filename) . '字节';
?>
运行该PHP会在D盘上生成test.xml文件(Win7 + XAMPP + IE9.0测试通过)

二.读取XML文件
以读取前文中生成的D:\\test.xml为例:

[php] <?php
//读取XML文件
// by MoreWindows( http://blog.csdn.net/MoreWindows )
$filename = "D:\\test.xml";
$article_array = array();

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->load($filename);

//得到<article>结点
$articles = $dom->getElementsByTagName("article");
echo '<article> 结点个数 ' . $articles->length;
foreach ($articles as $article)
{
$id = $article->getElementsByTagName("id")->item(0)->nodeValue;
$title = $article->getElementsByTagName("title")->item(0)->nodeValue;
$link = $article->getElementsByTagName("link")->item(0)->nodeValue;
$article_array[$id] = array('title'=>$title, 'link'=>$link);
}

//输出结果
echo "<pre>";
var_dump($article_array);
echo "</pre>";
?>
<?php
//读取XML文件
// by MoreWindows( http://blog.csdn.net/MoreWindows )
$filename = "D:\\test.xml";
$article_array = array();

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->load($filename);

//得到<article>结点
$articles = $dom->getElementsByTagName("article");
echo '<article> 结点个数 ' . $articles->length;
foreach ($articles as $article)
{
$id = $article->getElementsByTagName("id")->item(0)->nodeValue;
$title = $article->getElementsByTagName("title")->item(0)->nodeValue;
$link = $article->getElementsByTagName("link")->item(0)->nodeValue;
$article_array[$id] = array('title'=>$title, 'link'=>$link);
}

//输出结果
echo "<pre>";
var_dump($article_array);
echo "</pre>";
?>

上一页  1 2 3 

Tags:PHP 读写 XML

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接