在开发web应用时,为了减轻读写数据库的i/o开销,常常将一些配置信息存储在平面文件如:xml,json中,然后通过脚本语言如:php,javascript来操作这些文件。
php操作xml主要有两种方法:一种是通过dom,另一种是通过simplexml。这两种方法解析xml的原理都是分析整个xml文档,并提供api来访问树中元素。simplexml是php 5新增的特性,目的是为了简便完成一些xml的常见处理任务。
下面是一个简单示例,展示如何通过simplexml来格式化一组xml数据。
belgian waffles $5.95 two of our famous belgian waffles with plenty of real maple syrup 650 strawberry belgian waffles $7.95 light belgian waffles covered with strawberries and whipped cream 900 berry-berry belgian waffles $8.95 light belgian waffles covered with an assortment of fresh berries and whipped cream 900
复制代码
使用simplexml处理xml namepricedescriptioncalories
getname(); //var_dump($xml->children()); $record = ''; foreach ($xml->children() as $child) { $record .= ''. $child->attributes(). ' '; foreach ($child->children() as $item) { //var_dump($child); $record .= ''. $item .' '; } $record .= '
'; } echo $record;?>
复制代码