Is the output line breaking or newlines with json_encode?

I am new to JSON format, so please forgive my ignorance. But for some reason I need to add some line breaks to my json_encode array so that it parses multiple lines. I searched and searched, but nothing matched my situation.

It is displayed as:

Following formats accepted: www.website.com website.com website.net/something 

But I am looking for the output as follows:

 Website needs to be in the following formats: www.website.com website.com website.net/something 

I tried:

 echo json_encode( array( 'status' => 'failed', 'message' => "Website needs to be in the following formats:\n www.website.com\n website.com\n website.net/something" ), JSON_PRETTY_PRINT); 

But Javascript parses it as a literal string, so newline characters are ignored and output. Can I send data from PHP to javascript using the direct JSON format or do I need to use an array?

I also tried using <br /> .

EDIT:
I am outputting the following path:

 $.ajax({ url: "/forms/content_process.php", type:'POST', data: $(".content_cat").serialize(), processData: false, dataType: "json", success: function(response) { if (response.status == "failed") { $(".content_status").css( "background-color", "red" ); $(".content_status").text(response.message).slideDown("normal"); } else { $(".content_status").css( "background-color", "green" ); $(".content_status").text("Your category was submitted!").slideDown("normal"); } } }); 
+1
source share
2 answers

use \n to insert a newline character in a string. Do not add a new new line either.

 echo json_encode( array( 'status' => 'failed', 'message' => "Website needs to be in the following\nformats:\nwww.website.com\nwebsite.com\nwebsite.net/something" ), JSON_PRETTY_PRINT); 

than on the client side, before you insert it into your home, you will need to replace the newline characters with <br /> or use white-space: pre . alternatively, you can surround each line with <p></p> tags. for this see jQuery () text and newlines here .

+3
source

Looking back at this question, it became quite obvious to me how simple the solution was. The reason I had such a difficulty was because I used text , not html .

Of course, he didn’t output <br /> , I formatted it as text! This was the easiest way to do this for my situation.

 array( 'status' => 'failed', 'message' => "Website needs to be in the following formats:<br /> www.website.com<br /> website.com<br /> website.net/something" ), JSON_PRETTY_PRINT); $(".content_status").html(response.message).slideDown("normal"); 
+1
source

All Articles