PHP json_encode html元素包含不需要的空格

时间:2012-11-30 16:13:21

标签: php jquery html

我在这里遇到了问题。

index.php

ob_start();
include '../view/user.php';
$include = ob_get_clean();

echo json_encode(array(
"success" => true,
"status" => "ok",
"data" => $include));

user.php

<div>
<h2 class='workspace-name'>
<?php echo $name; ?>
</h2>
</div>

问题是如果我正确缩进user.php中的HTML元素(为了便于阅读),那么会有很多\r\n\t\t\t,前提是我使用jquery.get来获取JSON dataType。 / p>

如何摆脱/r/t/n?虽然屏幕上没有显示,但我觉得不对。有没有更好的解决方案? 有任何问题请放入评论中我将编辑此内容。感谢

3 个答案:

答案 0 :(得分:6)

为什么不使用str_replace()来替换这些字符。

"data" => str_replace(array("\n","\r","\t"),'',$include)));

编辑或者在处理像<a\thref='#'>Click\n\nHere</a>这样的HTML时使用以下内容(感谢@Salman A指出这一点)

"data" => str_replace(array("\n","\r","\t"),' ',$include)));

答案 1 :(得分:0)

这太丑了,但我就是这样做的:

$html = str_replace("\t",'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',$html);
$html = str_replace("\r\n",'<br />',$html);

我会关注这个以获得更好的答案。必须有正则表达方式。

答案 2 :(得分:-1)

$include = preg_replace("@[\\r|\\n|\\t]+@", "", ob_get_clean());
相关问题