Get href atribute and tag name for A element in HT

2019-08-12 08:30发布

I'm trying to get href attribute (url) and tag name from HTML using DOMDocument. I have the following code, but I listing parameters together:

$searchNodeA = $dom->getElementsByTagName('li');
$searchNodeHref = $dom->getElementsByTagName('a');

foreach($searchNodeA as $searchNode)
{
    $url = $searchNode->getAttribute('href');

    $acko = $searchNode->getElementsByTagName('a');
    $nazev = $acko->item(0)->nodeValue;

    echo "$nazev<br />";
}/**/

foreach($searchNodeHref as $searchNode)
{
    $url = $searchNode->getAttribute('href');
    echo "$url<br />";
}/**/

How do we suddenly announcing results?

$url - $nazev

1条回答
来,给爷笑一个
2楼-- · 2019-08-12 08:54

Use Xpath:

Select any li element

//li

Any a element inside a li element ...

//li//a

... with a href attribute

//li//a[@href]

Load, evaluate and iterate:

$dom = new DOMDocument();
$dom->loadHtml('<ul><li><a href="#link">caption</a></li></ul>');
$xpath = new DOMXpath($dom);

foreach ($xpath->evaluate('//li//a[@href]') as $a) {
  var_dump(
    [
      'text' => $a->nodeValue,
      'href' => $a->getAttribute('href')
    ]
  );
}

Output:

array(2) {
  ["text"]=>
  string(7) "caption"
  ["href"]=>
  string(5) "#link"
}
查看更多
登录 后发表回答