Php 使用特定类读取html表内容

Php 使用特定类读取html表内容,php,html,file-get-contents,Php,Html,File Get Contents,我有一个新闻页面显示我的新闻。我用表格显示标题 <table class="news"> <tr> <th>#</th> <th></th> </tr> <tr>...</tr> <tr>...</tr> </table> # ... ... 我在这一页有其他表格。但我想把这张表放到另一页。我搜索了一下,就这样找到了: $text

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

<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>");
$text=文件获取内容(“http://www.example.com/news");
回音条标签($text,“”);
输出包含新闻页面中的所有表。我的目标就是和班上的“新闻”一起吃饭。
我该怎么做呢?

回音条标签($text,“| | |”);
echo strip_tags($text, "<table class='news'>|<tr>|<th>|<td>");
这应该去除除这些标签之外的所有标签

echo strip_tags($text, "<table><tr><th><td>");
echo strip_标签($text,”);
这将剥离除字符串以外的所有内容:

回音条标签($text,“| | |”);
这应该去除除这些标签之外的所有标签

echo strip_tags($text, "<table><tr><th><td>");
echo strip_标签($text,”);
这将剥离除字符串以外的所有内容:


我创建了带有两个表的示例代码。您可以在末尾看到输出

<?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;
?>

我创建了带有两个表的示例代码。您可以在末尾看到输出

<?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;
?>

我建议您使用PHP DOMparser。@Kristiyan那么您能解释一下我该怎么做吗?那也许你可以给我看一份好的推荐信。您能显示您的html响应吗?我建议您使用PHP DOMparser。@Kristiyan,那么您能解释一下我该怎么做吗?那也许你可以给我看一份好的推荐信。你能显示你的html响应吗?太接近了。但是我想要主标签。不是纯文本。有什么解决方案吗?我已经更新了上面的代码,以返回tableIts如此接近的html。但是我想要主标签。不是纯文本。有什么解决方案吗?我已经更新了上面的代码以返回表的html