html DOM程序查找href值


html DOM program to find href value

我是php的新手,我被分配了一个项目,从以下HTML片段获取HREF值:

<p class="title">
<a href="http://canon.com/">Canon Pixma iP100 + Accu Kit
</a>
</p>

现在我使用以下代码:

$dom = new DOMDocument();
@$dom->loadHTML($html);
foreach($dom->getElementsByTagName('p') as $link) {
    # Show the <a href>
    foreach($link->getElementsByTagName('a') as $link)
    {
            echo $link->getAttribute('href');
            echo "<br />";
    }
}

这段代码为我提供了该页中所有<P>标记中所有<a href>的HREF值。我想解析<P>类"标题"只…我不能在这里使用Simple_HTML_DOM或任何类型的库。

或者,您可以使用DOMXpath。这样的:

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
// target p tags with a class with "title" with an anchor tag
$target_element = $xpath->query('//p[@class="title"]/a');
if($target_element->length > 0) {
    foreach($target_element as $link) {
        echo $link->getAttribute('href'); // http://canon.com/
    }
}

或者If如果你想遍历它。然后你需要手动搜索。

foreach($dom->getElementsByTagName('p') as $p) {
    // if p tag has a "title" class
    if($p->getAttribute('class') == 'title') {
        foreach($p->childNodes as $child) {
            // if has an anchor children
            if($child->tagName == 'a' && $child->hasAttribute('href')) {
                echo $child->getAttribute('href'); // http://cannon.com
            }
        }
    }
}