Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I JSON Encode HTML in PHP?

I am using AJAX and PHP to create a post and display it right away. My php code works to create the post but im having trouble doing the json encode to display the post that was just created. Encoding the html like this seems to add a \ before every / causing the html to break and display in a weird way. (I am using a json encode because in the event of there being an error I need a variable to know if it was an error and display the error in a different place than then posts)

Here is what i am trying to encode

$data = "<article class='post'><div class='post-head cf'>
         <a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a>
         <a href='' class='username'>".$rowuser['username']."</a></div>
         <img src='users/user_".$rowuser['user_id']."/posts/".$row['image']."' alt=''>
         <div class='post-body'>
         <div class='post-options'>
         <a class='likes' href=''>156 likes</a>
         </div>
         <p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p>
         <hr /><div class='cf'>
         <a class='like hide-text' href='javascript:;'>Like This Post</a>
         <form action='' class='comment'>
         <input type='text' placeholder='Add a comment'></form></div>
         </div></article>";

echo json_encode($data);
like image 360
Alex K Avatar asked Feb 05 '23 11:02

Alex K


1 Answers

Encoding the html like this seems to add a \ before every / causing the html to break

PHP is escaping the slashes while encoding. This can be preventing by adding a JSON_UNESCAPED_SLASHES flag when calling json_encode():

$data = "<html></html>";

$escaped = json_encode($data);
// string(16) ""<html><\/html>""
var_dump($escaped);

$unescaped = json_encode($data, JSON_UNESCAPED_SLASHES);
// string(15) ""<html></html>""
var_dump($unescaped);
like image 93
HPierce Avatar answered Feb 08 '23 03:02

HPierce