• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

php 使用SimpleXML处理XML

JavaScript 水墨上仙 2779次浏览

在开发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>


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明php 使用SimpleXML处理XML
喜欢 (0)
加载中……