php xpath:查询结果中的查询 - IT屋-程序员软件开发技术分享社区
- 首页
- PHP
- php xpath:查询结果中的查询
php xpath:查询结果中的查询
[英] php xpath: query within a query result
本文介绍了php xpath:查询结果中的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试解析一个 html 文件.
我们的想法是使用 title
和 desc
类获取 span,并在具有属性 class='thebest' 的每个 div 中获取它们的信息.
这是我的代码:
<头><title>test</title>头部><身体><div class="a">moshe1<div class="aa">haim</div>
<div class="a">moshe2</div><div class="b">moshe3</div><div class="thebest"><span class="title">title1</span><span class="desc">desc1</span>
<div class="thebest">span class="title">title2</span><span class="desc">desc2</span>
</html>KFIR;$doc = 新的 DOMDocument();@$doc->loadHTML($example);$xpath = new DOMXPath($doc);$expression="//div[@class='thebest']";$arts = $xpath->query($expression);foreach ($arts as $art) {$arts2=$xpath->query("//span[@class='title']",$art);echo $arts2->item(0)->nodeValue;$arts2=$xpath->query("//span[@class='desc']",$art);echo $arts2->item(0)->nodeValue;}echo "完成";
预期结果是:
title1desc1title2desc2done
我收到的结果是:
title1desc1title1desc1done
解决方案
使查询相对...以点开头(例如 ".//..."
).
foreach ($arts as $art) {//注意:单斜线(直接子)$titles = $xpath->query("./span[@class='title']", $art);if ($titles->length > 0) {$title = $titles->item(0)->nodeValue;回声 $title;}$descs = $xpath->query("./span[@class='desc']", $art);如果 ($descs-> 长度 > 0) {$desc = $descs->item(0)->nodeValue;回声 $desc;}}
I'm trying to parse an html file.
The idea is to fetch the span's with title
and desc
classes and to fetch their information in each div that has the attribute class='thebest'.
here is my code:
<?php
$example=<<<KFIR
<html>
<head>
<title>test</title>
</head>
<body>
<div class="a">moshe1
<div class="aa">haim</div>
</div>
<div class="a">moshe2</div>
<div class="b">moshe3</div>
<div class="thebest">
<span class="title">title1</span>
<span class="desc">desc1</span>
</div>
<div class="thebest">
span class="title">title2</span>
<span class="desc">desc2</span>
</div>
</body>
</html>
KFIR;
$doc = new DOMDocument();
@$doc->loadHTML($example);
$xpath = new DOMXPath($doc);
$expression="//div[@class='thebest']";
$arts = $xpath->query($expression);
foreach ($arts as $art) {
$arts2=$xpath->query("//span[@class='title']",$art);
echo $arts2->item(0)->nodeValue;
$arts2=$xpath->query("//span[@class='desc']",$art);
echo $arts2->item(0)->nodeValue;
}
echo "done";
the expected results are:
title1desc1title2desc2done
the results that I'm receiving are:
title1desc1title1desc1done
解决方案
Make the queries relative... start them with a dot (e.g. ".//…"
).
foreach ($arts as $art) {
// Note: single slash (direct child)
$titles = $xpath->query("./span[@class='title']", $art);
if ($titles->length > 0) {
$title = $titles->item(0)->nodeValue;
echo $title;
}
$descs = $xpath->query("./span[@class='desc']", $art);
if ($descs->length > 0) {
$desc = $descs->item(0)->nodeValue;
echo $desc;
}
}
这篇关于php xpath:查询结果中的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文