繁体   English   中英

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

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

应该

foreach ($rows as $row){

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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