PHP json_encode html element contains unwanted white space

I have a problem.

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 that if I correctly enter the html element in user.php (for readability), there will be a lot of \ r \ n \ t \ t \ t. if i use jquery.get to get json dataType. How to get rid of / r / t / n? Although it does not appear on the screen, but I do not feel good. Is there a better solution? Any question, please write in the comments, I will edit this. thanks

+4
source share
3 answers

Why not use str_replace () to replace these characters.

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

EDIT: Or use the following when working with HTML, for example <a\thref='#'>Click\n\nHere</a> (thanks to @Salman A for pointing this out)

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

It is so ugly, but I do it:

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

I will follow this for a better answer. There must be a regular way.

0
source
 $include = preg_replace("@[\\r|\\n|\\t] +@ ", "", ob_get_clean()); 
-1
source

All Articles