我有一个执行以下操作的 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 文档是一行,则内容将是一行;但是,我试图避免这种解决方案。
更新
问题得到了正确回答。这是完整的工作代码:
$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 "}";