【问题标题】:php - save a .html file formattedphp - 保存格式化的 .html 文件
【发布时间】:2013-06-20 09:18:11
【问题描述】:

这是我的问题: 我有我的 html 文档,我通过 ajax 发送两个值: "id" 和 "一个 html 字符串"

<div class="myClass"><h1 class="myClass">this is my html string </h1></div>

我在我的 .php 文件中收到这些数据,我将数据保存在一个 .html 文件中:

ajax 代码:

$(".button").on("click", function(e){
            e.preventDefault();
            var string = $(".htmlString").html();
            $.ajax({
                url: "data.php",
                type: "post",
                data: { 
                    ID: "correctID",
                    htmlString: string
                },
                success: function(){
                    alert('ok');
                },
                error:function(){
                    alert('error');
                }   
            }); 
        });

php代码:

if ($_POST['id'] == "correctID") {

    $fileLocation = $_SERVER['DOCUMENT_ROOT']  . "/www/file.html";
    $file = fopen($fileLocation,"w");
    $content = $_POST['htmlString'];
    fwrite($file,$content);
    fclose($file);
}

输出的.html文件内容如下:

<div class=\"myClass\"><h1 class=\"myClass\">

您看到的问题是引号前的“\”:

如何以正确的 html 格式保存我的文件?

<div class="myClass"><h1 class="myClass">

非常感谢,正在寻找并找到 DOMDocument::saveHTML 但我无法使用它,我对 PHP 很陌生..,我真的需要我的 html 文件中的类。

【问题讨论】:

  • 附注:作为h1 is a block element,您可能不需要将其插入div(而且具有相同的类)。
  • 是的,我知道,这就是例子,谢谢@Voitcus
  • 首先要做的是 var_dump($_POST) 以确保它不包含引号。这会告诉你错误是来自 js 还是 php。

标签: php html file format save


【解决方案1】:

您的问题是魔术引号,请使用 .htaccess 文件并放置以下指令 init 将其关闭。

php_flag magic_quotes_gpc Off

还可以使用一行来保存文件

$file_content;
file_put_contents("filename.html", $file_content);

【讨论】:

  • 我将 .htaccess 文件放在哪里?在根?还是在我保存 .html 文件的路径中? @DevZer0
  • 你可以把它放在根目录下或者和脚本文件同级
【解决方案2】:

您的问题是由 magic_quotes_gpc 引起的。

2 种可能的解决方案:

  • 禁用magic_quotes_gpc
  • 在 `$_POST['htmlString'] 上调用 stripslashes

【讨论】:

    猜你喜欢
    • 2010-10-22
    • 1970-01-01
    • 2010-10-31
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多