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

edt*_*edt 2 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 "}";
Run Code Online (Sandbox Code Playgroud)

生成的html文档如下所示:

{
foo: "<p>Lorem ipsum dolor 
sit amet, consectetur 
adipiscing elit.</p>"
}
Run Code Online (Sandbox Code Playgroud)

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

{
foo: "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>"
}
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点.我意识到如果原始的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 "}";
Run Code Online (Sandbox Code Playgroud)

D. *_*ans 7

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


Bjö*_*örn 5

做一个简单的替换?

$content = str_replace(
    array("\r\n", "\n", "\r"), 
    '',
    file_get_contents('some_html_doc.html')
);
Run Code Online (Sandbox Code Playgroud)

但是更好的主意是立即执行json_encode()

$content = json_encode(file_get_contents('some_html_doc.html'));
Run Code Online (Sandbox Code Playgroud)