[英]PHP json_encode html element contains unwanted white space
I have a problem here. 我这里有问题。
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>
The problem is if I indent the HTML element in user.php
properly (for readability), there will be a lot of \\r\\n\\t\\t\\t
, provided I use jquery.get
to get JSON dataType. 问题是如果我正确地缩进
user.php
的HTML元素(为了便于阅读),将会有很多\\r\\n\\t\\t\\t
,如果我使用jquery.get
来获取JSON dataType。
How do I get rid of the /r/t/n
? 如何摆脱
/r/t/n
? Although it doesn't display on screen I don't feel right about it. 虽然屏幕上没有显示,但我觉得不对。 Is there any better solution?
有没有更好的解决方案? Any question please drop in the comment I will edit this.
有任何问题请放入评论中我将编辑此内容。 thanks
谢谢
Why not use str_replace() to replace those characters. 为什么不使用str_replace()来替换这些字符。
"data" => str_replace(array("\n","\r","\t"),'',$include)));
EDIT: Or use the following when dealing with HTML like <a\\thref='#'>Click\\n\\nHere</a>
(thanks to @Salman A for pointing this out) 编辑:或者在处理HTML时使用以下内容,例如
<a\\thref='#'>Click\\n\\nHere</a>
(感谢@Salman A指出这一点)
"data" => str_replace(array("\n","\r","\t"),' ',$include)));
This is so ugly, but it is how I do it: 这太丑了,但我是这样做的:
$html = str_replace("\t",' ',$html);
$html = str_replace("\r\n",'<br />',$html);
I'll be following this for a better answer. 我会关注这个以获得更好的答案。 There must be a regex way.
必须有正则表达方式。
$include = preg_replace("@[\\r|\\n|\\t]+@", "", ob_get_clean());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.