如何将字符串写入包含 HTML 标记的文件


how to write a string to a file that contains html tags

我已经通过php文件系统创建了一个新的.php文件,现在我正在尝试将html代码写入文件。这是代码

        $file = 'django unchained.php';
        if($handle = fopen($file , 'a'))
        {
            $text = htmlentities("<a href='"index.php'">Just link</a>");
            echo $text; // here it shows up fine in webpage.
            file_put_contents($file , $text); // after writing to file it doesnot appear the same in .php file
            fclose($handle);    
        }

正如上面的评论中提到的,当我在网页中回显它时,它显示正常,但当相同的字符串写入文件时看起来不一样。

提前谢谢。

如果你打开HTML页面的源代码,你会看到相同的文本,你会看到django unchained.php

&lt;a href=&quot;index.php&quot;&gt;Just link&lt;/a&gt;

此文本由 htmlentities 函数生成,该函数将特殊 HTML 字符转换为其实体等效项。这种行为是绝对可预测和正确的。

如果要输出以提交未引用的文本,请执行以下操作:

<?php
$file = 'django unchained.php';
$text = "<a href='"index.php'">Just link</a>";
echo htmlentities($text); // here it shows up fine in webpage.
file_put_contents($file , $text) or die('Error opening file');

看起来你的锁有问题,试试这段代码:

$file = 'django unchained.php';
$text = "<a href='"index.php'">Just link</a>";
file_put_contents($file , $text) or die('Cannot open file for writing');

注意:这里不需要 Fopen、Fclose、HTMLSpecialchars