php domDocument xpath 从表中提取链接


php domDocument xpath extract links from table

我正在尝试使用domDocument和xpath来提取表格的内容,包括某些单元格中链接的href属性。 下面的代码绘制一个空白。

<?php
$url_content='<html>
<body>
<table class="txtable">
<tbody>
    <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
        <th>Col 4</th>
    </tr> 
    <tr>
        <td><a href="www.example1.com">link 1</a></td>
        <td>31</td>
        <td>34</td>
        <td>Blue</td>
    </tr> 
    <tr>
        <td><a href="www.example2.com">link 2</a></td>
        <td>41</td>
        <td>44</td>
        <td>Red</td>
    </tr>
</tbody>
</table>
</body>
</html>';
$doc = new DOMDocument();
@$doc->loadHTML($url_content);
$finder = new DomXPath($doc);
$rows = $finder->query("//table[@class='txtable']/tbody/tr");
foreach ($rows->childNodes AS $row){
foreach($row->childNodes AS $cell){
    if (($cell->nodeName == "td") OR ($cell->nodeName == "th")){
        echo $cell->nodeValue."<br>";   
    } else {
        echo $cell->getAttribute('href')."<br>";
    }
}
}

我担心我不了解有关 xpath 或 domDocument 的基本知识。 感谢帮助。

我希望$rows是我可以使用foreach迭代的行的集合。 echo 语句应显示每个 .

如果孩子不是"td"或"th",在这种情况下它必须是"a",那么我想回显出 href 属性

我在浏览器中一无所获

如果我从 php 运行,我会得到

PHP 注意:未定义的属性:DOMNodeList::$childNodes 在/var/www/follow/php/domtest.php 第 35 行PHP 警告:在第 35 行的/var/www/follow/php/domtest.php 中为 foreach() 提供的参数无效

foreach ($rows->childNodes AS $row){

应该是

foreach ($rows as $row){