Php 用于查找href值的html DOM程序

Php 用于查找href值的html DOM程序,php,html,domdocument,Php,Html,Domdocument,我是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->getElementsB

我是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 />";
    }
}
$dom=newdomdocument();
@$dom->loadHTML($html);
foreach($dom->getElementsByTagName('p')作为$link){
#展示
foreach($link->getElementsByTagName('a')作为$link)
{
echo$link->getAttribute('href');
回声“
”; } }
此代码为我提供该页面中所有
标记中所有
的HREF值。我只想用“title”类解析

,我不能在这里使用简单的HTML\U 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/
    }
}
或者如果你想穿过它。然后您需要手动搜索它

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
            }
        }
    }

}

非常感谢!如果我想获取标签的文本值,只需一个小查询,意思是“Canon Pixma iP100+Accu Kit”…我应该怎么做?@JoyeetaSinharay如果你想使用
$child->nodeValue
,它应该得到text@JoyeetaSinharay当然很高兴它起了作用