如何使用xPath进行跟踪

时间:2017-02-20 08:08:55

标签: php dom xpath

我得到了div&#34; rso&#34;使用getElementById(&#39; rso&#39;)在php Dom中的数据但是php不允许通过&#34; ClassName&#34; ,我需要得到所有&#34;孩子&#34; <div class =srg>然后标记&#34; href&#34;在里面。

<div id=”rso”>
    <div class= “_Nid”>
        <div class = “srg”>
            <div class =”g”> 
                <div class=”rc”>
                    <h3 class = “r”>
                        <a href >
                    </h3>
                </div> 
            </div>
            <div class =”g”>...</div>
            <div class =”g”>...</div>
            <div class =”g”>...</div>
        </div>
    </div>
</div>
你可以告诉我们如何做到这一点。或者如果它可以在这里工作,将使用什么xPath。

2 个答案:

答案 0 :(得分:1)

<?php
$html = <<<HTML
<div id="rso">
    <div class="_Nid">
        <div class="srg">
            <div class="g"> 
                <div class="rc">
                    <h3 class="r">
                        <a href="http://my.site.com/lol.txt" >
                    </h3>
                    <h3 class="r">
                        <a href="http://my.site.com/lol2.txt" >
                    </h3>
                    <h3 class="r">
                        <a href="http://my.site.com/lol23.txt" >
                    </h3>
                </div> 
            </div>
            <div class="g">...</div>
            <div class="g">...</div>
            <div class="g">...</div>
        </div>
    </div>
</div>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html);
$domxpath = new DOMXPath($dom);
$filtered =  $domxpath->query('//div[@class="srg"]//a/@href');
foreach ($filtered as $item) {
    echo "$item->value\n";
}

答案 1 :(得分:0)

请尝试以下//div[@class="srg"]//a/@href

reset_button