0

我需要将 HTML 转换为 txt 输出。像下面的示例,通过 php ,是否可能?

前任:

HTML 格式:

<table>
    <tr>
        <td>Srinivasan-1</td>
        <td>welcome-1</td>
    </tr>
    <tr>
         <td>Srinivasan-2</td>
         <td>welcome-2</td>
    </tr>
</table>

需要这种txt格式的输出

Srinivasan-1      welcome-1  Test -1   
Srinivasan-2      welcome-2  Test -2
4

4 回答 4

0

如果您希望文本保持表格中的格式,那么解决方案将非常复杂。使用内置 PHP 函数,您将无法保持列之间的均匀间距,因为它将不再是表格,而只是文本。

您可以做的是使用strip_tags()函数摆脱 HTML。可能需要在列之间放置制表符以使其看起来好像仍然是一个表。这是我掀起的一个功能:

<?php
    function StripHtmlFromTable($html_in)
    {
        $html_in = str_replace("</td>", "\t", $html_in); // Space the columns.
        $html_in = str_replace("</tr>", "\n", $html_in); // Put each row on a new line.
        $text_out = strip_tags($html_in);

        return $text_out;
    }
?>

我在我的电脑上测试了脚本,这是输出的图像:

该功能在起作用,相信这就是你想要它做的吗?

我必须将输出放在<pre>标签内,以便您可以看到该函数如何使用空格来格式化文本。输出看起来与您的示例输出完全一样,我希望这是您正在寻找的。

于 2013-01-07T07:56:19.623 回答
0

您可以使用一组正则表达式并将它们替换为换行符和制表符:

<?php
$raw = '<table>
    <tr>
        <td>Srinivasan-1</td>
        <td>welcome-1</td>
    </tr>
    <tr>
         <td>Srinivasan-2</td>
         <td>welcome-2</td>
    </tr>
</table>';
    $patterns = array(
        '/[\n\t]/si', /* remove existing whitespace and linebreaks */
        '/<tr.*?>/s', /* beginning of a row (new line) */
        '/<td.*?>([^<]+)<\/td>/s' /* all cells*/
    );
    $replaces = array(
        "", /* remove whitespace */
        "\n", /* add a new line for each tr */
        "\t$1" /* add a indent and the content of each cell */
    );
    // run the preg replace and strip all other tags
    $text = strip_tags(preg_replace($patterns,$replaces,$raw));
    echo $text;
?>
于 2013-01-07T07:59:21.563 回答
0

你能试试这个吗?

  <?php
    $ones= "<table><tr><td>Srinivasan-1</td><td>welcome-1</td></tr><tr><td>Srinivasan-2</td><td>welcome-2</td></tr></table>";

    $ones= strip_tags($ones);

    $file = fopen("test.txt","w");

    fwrite($file,$ones);

    fclose($file);
    ?>

无论如何,它不会按您的意愿输出。但我希望这是写入文件的基本方法。

于 2013-01-07T07:41:15.340 回答
0

嗯... PHP strip_tags 函数是否由于某种原因不够用?

http://php.net/manual/en/function.strip-tags.php

您可以使用 str_replace 分别将每个关闭的 td 和 tr 替换为选项卡和 CRLF 以获得您似乎正在寻找的输出布局。

于 2013-01-07T07:36:57.157 回答