Php 如何使用DOMDocument获取锚文本?

Php 如何使用DOMDocument获取锚文本?,php,domdocument,Php,Domdocument,假设我有这个html: <a href="http://example.com">Test</a> 然后我运行以下代码: $dom = new DomDocument(); @$dom->loadHTML($html); $urls = $dom->getElementsByTagName('a'); foreach ($urls as $url) { //echo "<br> {$url->getA

假设我有这个html:

<a href="http://example.com">Test</a>
然后我运行以下代码:

$dom = new DomDocument();
@$dom->loadHTML($html);
$urls = $dom->getElementsByTagName('a');
foreach ($urls as $url)
{
    //echo "<br> {$url->getAttribute('href')} , {$url->getAttribute('title')}";
    foreach ($url->attributes as $a)
    {
        echo "<br>$a->name is $a->value";
    }
    echo "<hr><br>";
}
foreach($url作为$url)
{
//echo“
{$url->getAttribute('href')},{$url->getAttribute('title')}”; foreach($url->attributes as$a) { echo“
$a->name is$a->value”; } 回声“

”; }
当我这样做时,我只看到“href”作为url的属性,无法获取“锚文本”(在上面的“Test”案例中)。如何获取链接的锚文本?

使用:

文本“Test”实际上是一个DOM文本节点,因此您可以通过$url的子节点获取内容

您可以查看此帖子以了解解决方案:

foreach($url作为$url){
$attributes=$url->attributes;
echo“
$url->nodeValue是$attributes->href”; }
这实际上是为了获得innerHTML,如果您只需要@lonesomeday指出的内部文本,您可能需要使用nodeValue。我有一个图像标记作为链接的锚文本。如果我使用nodeValue,它不会返回任何内容。我正在使用find('a[href=url]')获取匹配的锚链接。如何获取图像标签??textContent不返回任何内容。它应该返回类似于但不正确的结果。它现在返回图像标记。谢谢你,亨德里克斯
echo $url->nodeValue;
foreach ($urls as $url) {
    $attributes = $url->attributes;
    echo "<br>$url->nodeValue is $attributes->href";
} 
here is two line code may it help some one

$html   =   file_get_html($link);
foreach($html->find("a") as $key=>$val)
{
  echo $val->src;
  echo '\n';   
}