php - 用 php domdocument 得到一个完整的表格并打印出来

我想使用 php domddocument 从给定的 url 获取一个 id = 'myid' 的完整 html 表,并将其打印到我们的网页,我该怎么做?

我正在尝试使用以下代码获取表格,但无法获取 trs(表格行)和 tds(表格数据)和其他内部 html。

$xml = new DOMDocument();

@$xml->loadHTMLFile($url);
foreach($xml->getElementById('myid') as $table)
{
  // now how to get tr and td and other element ?
  // i am getting other element like :-
   $links = $table->getElementsByTagName('a');
   foreach($links as $innerAnchor)
  {
    //doing something with anchor tag...
   }

}

需要帮助。

我是 php domddocument 的新手。

非常感谢。

最佳答案

正如我所说,最好不要使用 getElementById。更好地分析我的测试样本;它有效

$html = "<table ID='myid'><tr><td>1</td><td>2</td></tr><tr><td>4</td><td>5</td></tr><tr><td>7</td><td>8</td></tr></table>";

$xml = new DOMDocument();
$xml->validateOnParse = true;
$xml->loadHTML($html);

$xpath = new DOMXPath($xml);
$table =$xpath->query("//*[@id='myid']")->item(0);

// for printing the whole html table just type: print $xml->saveXML($table); 

$rows = $table->getElementsByTagName("tr");

foreach ($rows as $row) {
  $cells = $row -> getElementsByTagName('td');
  foreach ($cells as $cell) {
    print $cell->nodeValue; // print cells' content as 124578
  }
}

https://stackoverflow.com/questions/7429136/

相关文章:

android - 如何显示内部存储中的位图?

php - 我可以将匿名函数放在 PHP 的数组中吗?

.htaccess - Htaccess URL Rewrite 捕获 2 或 5 个字符(但不是

vhdl - 如何在 VHDL 中制作一个简单的 4 位奇偶校验器?

qt - 如何使用QT从打印机打印图像文件

c# - 如何从后面的 C# 代码更新 WPF 绑定(bind)的值?

assembly - 将二进制转换为十进制并在汇编中显示

git - 当我用分支推送时,.gitignore 不会忽略文件

asp.net - 检查文件夹在 C#.net 中是否只读

android - 如何将 OutputStream 转换为文件?