php xpath:查询结果中的查询

php xpath:查询结果中的查询,php,xpath,Php,Xpath,我正在尝试解析一个html文件 其思想是使用title和desc类获取span,并在每个具有class='thebest'属性的div中获取span的信息 这是我的密码: <?php $example=<<<KFIR <html> <head> <title>test</title> </head> <body> <div class="a">moshe1 <div class=

我正在尝试解析一个html文件

其思想是使用
title
desc
类获取span,并在每个具有class='thebest'属性的div中获取span的信息

这是我的密码:

<?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";
我收到的结果是:

title1desc1title1desc1done

尝试
textContent

foreach ($arts as $art) {
    echo $art->textContent;
}
textContent
返回此节点及其子节点的文本内容

或者,将XPath更改为

$expression="//div[@class='thebest']/span[@class='title' or @class='desc']";
$arts = $xpath->query($expression);

foreach ($arts as $art) {
    echo $art->nodeValue;
}

这将获取div的跨度子级,其中类最好具有title或desc类。

使查询相对。。。以点开头(例如,
“//…”

$expression="//div[@class='thebest']/span[@class='title' or @class='desc']";
$arts = $xpath->query($expression);

foreach ($arts as $art) {
    echo $art->nodeValue;
}
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;
    }
}