Reputation: 13
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
Upvotes: 1
Views: 1224
Reputation: 19502
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"
}
Upvotes: 1