读取xml的一个简单例子
aa.xml
复制内容到剪贴板
代码:
<?xml version="1.0" encoding="utf-8"?>
<result>
<name id="10">张三</name>
<mobile>123456789</mobile>
<id>52</id>
</result>test.php
复制内容到剪贴板
代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head><?php
$parser = xml_parser_create('UTF-8'); //创建一个parser编辑器
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
xml_set_element_handler($parser, "startElement", "endElement");//设立标签触发时的相应函数 这里分别为startElement和endElenment
xml_set_character_data_handler($parser, "characterData");//设立数据读取时的相应函数
$xml_file="aa.xml";//指定所要读取的xml文件,可以是url
if (!($filehandler = fopen($xml_file, 'r'))) {
die("无法打开 $xml_file 文件进行解析!n");
}
while ($data = fread($filehandler, 4096))
{
xml_parse($parser, $data, feof($filehandler));
}//每次取出4096个字节进行处理
fclose($filehandler);
xml_parser_free($parser);//关闭和释放parser解析器
$name=false;
$position=false;
function startElement($parser_instance, $element_name, $attrs) //起始标签事件的函数
{
global $name,$mobile,$id;
if($element_name=="NAME")节点名称
{
if($attrs[ID])//属性
{
$id=" id ".$attrs[ID];
}
$name=true;
$mobile=false;
echo "名字:";
}
if($element_name=="MOBILE")
{$name=false;
$mobile=true;
echo "手机:";
}
}
function characterData($parser_instance, $xml_data) //读取数据时的函数
{
global $name,$mobile,$id;
if($mobile)
echo $xml_data."<br>";
if($name)
echo $xml_data.$id."<br>";
}
function endElement($parser_instance, $element_name) //结束标签事件的函数
{
global $name,$mobile;
$name=false;
$mobile=false;
}
?></html>读取属性
复制内容到剪贴板
代码:
<?php
/*example.php
$xml = <<<XML
<?xml version="1.0" encoding="GB2312" standalone='yes'?>
<result>
<name id="10" value="的光">的光</name>
<mobile>123546789</mobile>
<id>52</id>
</result>
XML;*/
?>
<meta http-equiv="Content-Type" content="text/html;" />
<?php
include 'example.php';
$xmlr = simplexml_load_string($xml);//simplexml_load_string -- Interprets a string of XML into an object
echo ($xmlr->name[0][id]);
echo ($xmlr->name[0][value]);
?>前些天leo还帮着改过,嘿嘿
之前只用过js调用。高手们详细介绍下php解析和调用XML吧!
[
本帖最后由 傲慢的上校 于 2007-9-11 13:17 编辑 ]