简体   繁体   中英

Get href atribute and tag name for A element in HTML using DOMDocument

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM