PHP XPath(xml中快速查找)

18 篇文章 0 订阅
13 篇文章 0 订阅

XPath:XML'S Path,是一门在 XML 文档中快速查找(定位)信息的语言。XPath 用于在 XML 文档中通过元素和属性进行导航。

/ : 表示从根结点选取。(类似Linux命令)

// : 不论层次。

. : 选取当前结点。

.. : 选取当前结点的父节点。

@ : 选取属性。

xpath1.php:

<?php
$dom = new DOMDocument('1.0','utf-8');
$dom->load('rss.xml');
//实例化domxpath对象
$xpath = new DOMXPath($dom);

//书写路径表达式
$query = "//title"; // "//"不考虑层次。
$query = "/title"; //找不到,因为这种写法意味着从根节点title开始找,但它不是根节点
$query = "/bookstore/book/title";   //根节点bookstore下的book节点下的title节点
$query = "/bookstore//title";   //根节点bookstore下的所有title节点

$query = "//title";   // 所有title节点
$query = "//item/title";  // item下的title节点
$query = "/rss/channel/title";  //rss是根节点
$query = "/rss//title";

$res = $xpath->query($query);   //通过query方法,返回DOMNodeList类型。
var_dump($res);

bookstore.xml:

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
    <book category="COOKING">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="CHILDREN">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="WEB">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>
rss.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE rss SYSTEM 'rss.dtd'>
<rss version='2.0'>
	<channel>
		<title>PHP学院</title>
		<link>http://php.baidu.cn</link>
		<description>学PHP</description>
		<language>zn-cn</language>
		<item>
			<title>标题1</title>
			<link>http://php.baidu.cn/1.php</link>
			<pubDate>2013-05-09 10:23:40</pubDate>
			<description>正文1</description>
		</item>
		<item>
			<title>标题2</title>
			<link>http://php.baidu.cn/2.php</link>
			<pubDate>2013-05-09 10:23:40</pubDate>
			<description>正文2</description>
		</item>
	</channel>
</rss>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值