domdocument xpath захватывает первое имя якоря tr и href без идентификатора или класса

Извините за мой английский.

Я хочу прочитать имя якоря и href с первого «tr». Href я получаю, но не название …

Кто-нибудь может мне помочь?

$dom      = new domDocument;
@$dom->loadHTML($content2);
$dom->preserveWhiteSpace = true;
$xpath                   = new DOMXPath($dom);
$rows                    = $xpath->query('//tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
foreach ($cols as $col) {
$test = $col->nodeValue;
if ($xpath->evaluate('count(./a)', $col) > 0) { // check if an anchor exists
$link = $xpath->evaluate('string(./a/@href)', $col); // if there is, then echo the href value
}

}
}

<table width="100%" border="0">
<tr>
<td style="width:20px;"><img src="https://web-answers.ru/wp-content/uploads/2019/02/gfx/programm.png" style="cursor: pointer;"> </td>
<td style="width:415px;"><a href="?id=492488" onmouseover="Kurzinfo(492488)" onmouseout="hideit(492488)">Wondershare Filmora - 8.2.2.1 Patch</a> </td>
<td nowrap="nowrap" style="text-align:right;">Appz </td>
<td style="width:40px;text-align:right;">220 </td>
<td style="width:20px;"> MB </td>
<td style="width:150px;text-align:right;" nowrap="nowrap">21.05.2017 10:23:48 Uhr </td>
</tr>
<tr>

0

Решение

Я полагаю, вы хотите получить Wondershare Filmora - 8.2.2.1 Patch, для этого вы можете использовать text()т.е.

$dom = new domDocument;
@$dom->loadHTML($content2);
$dom->preserveWhiteSpace = true;
$xpath = new DOMXPath($dom);
$rows = $xpath->query('//tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
foreach ($cols as $col) {
$test = $col->nodeValue;
if ($xpath->evaluate('count(./a)', $col) > 0) { // check if an anchor exists
$link = $xpath->evaluate('string(./a/@href)', $col); // get the href value
$text = $xpath->evaluate('string(./a/text())', $col); // get the href text value
}
}
}

PHP Demo

2

Другие решения

Я хочу прочитать имя якоря и href с первого «tr». Href я получаю, но не название

Первый tr может быть выражено как //table//tr[1], Точно так же первый якорь первого tr можно получить с помощью (//table//tr[1]/td//a)[1] выражение, например:

$anchor_list = $xpath->query('(//table//tr[1]/td//a)[1]');

где $anchor_list это либо случай DOMNodeList, или же FALSE, Элементы (экземпляры DOMElement) можно получить с помощью [] оператор.

if ($anchor_list && $anchor_list->length) {
$a = $anchor_list[0];
}

имеющий DOMElement мы можем легко получить доступ к его атрибутам через attributes имущество:

$href = $a->attributes->getNamedItem('href');

var_dump($href ? $href->textContent : "(none)");
var_dump($name ? $name->textContent : "(none)");

Если вы хотите получить внутренний текст узла привязки, используйте textContent имущество:

var_dump($a->textContent);
1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector