您当前的位置: 首页 > 学无止境 > XML与XSLT 网站首页XML与XSLT
2.php解析xml
发布时间:2017-04-30 12:41:32编辑:雪饮阅读()
php解析xml文档(或字符串)示例:
index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<?php
$xml=file_get_contents("index.xml");
//使用xml类的构造函数,给构造函数传入要读取xml文档的版本号与编码。
$dom=new DOMDocument('1.0','utf-8');
//载入xml
$dom->loadXML($xml);
//读取一个xml标签(返回一个domNodelist)
$GirlfriendList=$dom->getElementsByTagName("Girlfriend");
//获取第一个节点
$outone=$GirlfriendList->item(0);
//获取第一个节点的文本节点
$text=$outone->firstChild;
//获取文本节点值
$textVal=$text->wholeText;
//或者$textVal=$text->nodeValue;也可以获取
//若该标签内部有cdata,则直接获取cdata中的内容
//获取Girlfriend标签的dmj属性值
$outone->getAttribute("dmj");
echo $textVal;
?>
</body>
</html>
index.xml:
<?xml version="1.0" encoding="utf-8"?>
<xy>
<name>雪饮</name>
<sex>男</sex>
<Girlfriend>杜敏捷(杜姐姐)</Girlfriend>
<major>电子商务</major>
</xy>
关键字词:php,xml
上一篇:1.xml介绍与书写规范
下一篇:3.xml的创建