【问题标题】:read html table content with specific class [duplicate]读取具有特定类的html表格内容[重复]
【发布时间】:2015-08-14 14:34:56
【问题描述】:

我有显示我的新闻的新闻页面。我用表格来显示标题。

<table class="news">
<tr>
    <th>#</th>
    <th></th>
</tr>
<tr>...</tr>
<tr>...</tr>
</table>

我在此页面中还有其他表格。但我想在另一个页面中获取此表。我搜索并找到了这种方式:

$text = file_get_contents("http://www.example.com/news");
echo strip_tags($text, "<table><tr><th><td>");

输出包含新闻页面中的所有表格。我的目标只是带有“新闻”类的表格。
我该怎么做?

【问题讨论】:

  • 我建议你使用 PHP DOMparser。
  • @Kristiyan 那么你能解释一下我该怎么做吗?那么也许你可以给我一个很好的参考。 tnx.
  • 你能显示你的 html 响应吗?

标签: php html file-get-contents


【解决方案1】:

我创建了包含两个表的示例代码。可以看到最后的输出

<?php
$html = <<<EOT
<table class="news" border='1'>
<tr>
<th>#</th>
<th></th>
</tr>
<tr><td>New 1 - first </td><td>New 1 - second </td></tr>
<tr><td>New 1 - fifth </td><td>New 1 - forth</td></tr>

</table>
<table class="another_news" border='1'>
<tr>
<th>#</th>
<th></th>
</tr>
<tr><td>Another New 1 - first </td><td>Another New 1 - first </td></tr>
<tr><td>AnotherNew 1 - first </td><td>Another New 1 - first </td></tr>

</table>
EOT;
echo $html;
echo "<hr>";
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your HTML
$xpath = new DOMXPath($doc);
// returns all tables with class news
$tables = $xpath->query('//table[@class="news"]');
$requiredTable = ''; // This will html of tables
foreach ($tables as $table) {
    $requiredTable .=  $doc->saveXML($table);
}
echo $requiredTable;
?>

这应该在$requiredTable变量中打印表格

【讨论】:

  • 它是如此接近。但我想要主要标签。不是纯文本。有什么解决办法吗?
  • 我已经更新了上面的代码来返回表格的html
【解决方案2】:
echo strip_tags($text, "<table class='news'>|<tr>|<th>|<td>");

这应该去除除那些之外的所有标签

echo strip_tags($text, "<table><tr><th><td>");

这将删除除字符串之外的所有内容:

&lt;table&gt;&lt;tr&gt;&lt;th&gt;&lt;td&gt;

【讨论】:

    猜你喜欢
    • 2019-11-18
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2012-04-18
    • 2018-01-25
    • 1970-01-01
    • 2017-06-22
    相关资源
    最近更新 更多