在开发Web应用时,为了减轻读写数据库的I/O开销,常常将一些配置信息存储在平面文件如:XML,json中,然后通过脚本语言如:PHP,javascript来操作这些文件。
PHP操作XML主要有两种方法:一种是通过DOM,另一种是通过SimpleXML。这两种方法解析XML的原理都是分析整个XML文档,并提供API来访问树中元素。SimpleXML是PHP 5新增的特性,目的是为了简便完成一些XML的常见处理任务。
下面是一个简单示例,展示如何通过SimpleXML来格式化一组XML数据。
xml文件
<?xml version="1.0" encoding="UTF-8"?> <!-- Edited with XML Spy v2007 (http://www.altova.com) --> <breakfast_menu> <food id="1"> <name>Belgian Waffles</name> <price>$5.95</price> <description>two of our famous Belgian Waffles with plenty of real maple syrup</description> <calories>650</calories> </food> <food id="2"> <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <description>light Belgian waffles covered with strawberries and whipped cream</description> <calories>900</calories> </food> <food id="3"> <name>Berry-Berry Belgian Waffles</name> <price>$8.95</price> <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> <calories>900</calories> </food> </breakfast_menu>
使用SimpleXML处理XML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用simpleXML处理XML</title>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0" width="700">
</tbody>
<tr bgcolor="green">
<th width="5%"> </th>
<th width="20%">name</th>
<th width="10%">price</th>
<th width="55%">description</th>
<th width="10%">calories</th>
</tr>
<?php
// 使用simpleXML处理XML
$xml = simplexml_load_file('./simple.xml');
//var_dump($xml);
//echo $xml->getName();
//var_dump($xml->children());
$record = '';
foreach ($xml->children() as $child)
{
$record .= '<tr><td>'. $child->attributes(). '</td>';
foreach ($child->children() as $item)
{
//var_dump($child);
$record .= '<td>'. $item .'</td>';
}
$record .= '</tr>';
}
echo $record;
?>
</tbody>
</table>
</body>
</html>
