从PHP变量值中删除换行符和换行符?

时间:2009-07-14 13:32:25

标签: php json file-get-contents

我有一个执行以下操作的PHP脚本:

  • 使用file_get_contents()获取html文件的内容
  • 回声JSON对象

问题是从file_get_contents获得的值是多行的。它需要全部在一行才能采用正确的JSON格式。

例如

PHP文件:

$some_json_value = file_get_contents("some_html_doc.html");

echo "{";
echo "\"foo\":\"$some_json_value\"";
echo "}";

生成的html文档如下所示:

{
foo: "<p>Lorem ipsum dolor 
sit amet, consectetur 
adipiscing elit.</p>"
}

我的目标是让生成的html文档看起来像这样(值是一行,而不是三行)

{
foo: "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>"
}

如何做到这一点。我意识到如果原始的html doc是一行,内容将是一行;但是,我正试图避免这种解决方案。

更新

问题得到了正确回答。这是完整的,有效的代码:

$some_json_value = file_get_contents("some_html_doc.html");
$some_json_value = json_encode($some_json_value); // this line is the solution

echo "{";
echo "\"foo\":\"$some_json_value\"";
echo "}";

3 个答案:

答案 0 :(得分:7)

除了换行符之外的其他字符会导致问题(例如双引号和反斜杠),因此不仅仅去除换行符,最好正确编码JSON。对于PHP&gt; = 5.2,有内置的json_encode函数,并且有适用于旧版PHP的库(参见例如http://abeautifulsite.net/notebook/71

答案 1 :(得分:5)

做一个简单的替换?

$content = str_replace(
    array("\r\n", "\n", "\r"), 
    '',
    file_get_contents('some_html_doc.html')
);

但更好的想法是立即做json_encode();

$content = json_encode(file_get_contents('some_html_doc.html'));

答案 2 :(得分:0)

您可以使用“”替换所有出现的\ n和\ r \ n。查看preg_replace