How to parse json with inline html? - php

I'm passing data between two systems. In PHP, I have a function that formats text like this:
function cleanText($string) {
return '<p>'.trim(preg_replace('/\n+/', '</p><p>', $string)).'</p>';
}
This is how I ouput the php-array as json:
echo json_encode($data);
I then pass that data in Ajax, so I receive the text like this:
{"content":"<p>Hej! Detta ska nu vara ordnat! Ledsen f\u00f6r besv\u00e4r.<\/p>"}
In the other system I'm using Node.js and parse like this:
json = JSON.parse(json);
But this will escape the HTML, I don't want that, I want to output the string as HTML. How should I do this? Should I indicate the markup in a different way in PHP or can I somehow parse the Ajax keeping the HTML?

json_encode will transform an array into proper JSON. I would first turn it into array, then json_econde it. Your PHP should be something like this:
function cleanText($string) {
return '<p>' . trim(preg_replace('/\n+/', '</p><p>', $string)) . '</p>';
}
$str = cleanText("My string");
echo json_encode(array("content" => $str));
once you do that, JS will then be able to use JSON.parse(data), resulting in something like this:
Object {content: "<p>My string</p>"}

Related

Removing all quotes from JSON file using PHP

I want to remove all double quotes from a JSON file using PHP.
The following code outputs all the variables to a JSON file named example.json:
$var_geoJSON = 'var geoJSON = ';
file_put_contents('jsonfun.json', $var_geoJSON);
file_put_contents('jsonfun.json', json_encode($geojson, JSON_NUMERIC_CHECK), FILE_APPEND);
I was trying to get it to output something like this:
var geoJSON = {...}
Yet it outputs something like this:
"var geoJSON = " {...}
I am currently working with geoJSON to output to the open source leaflet.js mapping library, and the syntax requires that I have var geoJson = {...} instead of having "var geoJSON = "{...}.
I have tried using the PHP command preg_replace() replacing all the "" with spaces, yet that still didn't work and it outputted the same thing with the double quotes.
Any ideas?
Just use str_replace function http://www.w3schools.com/php/func_string_str_replace.asp example:
$result = str_replace('"', '', $json)

Formatting JSON formatted text file in PHP

So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]

PHP jSon data clean values for unwanted white spaces

Below is my JSON data which i get it by using
$json = json_encode($array);
my JSON Data;
{
"id":"352",
"date":"2013-12-25 01:10:06",
"category":"2",
"subtitle":null,
"description":" This text is description... ",
"hit":"144",
"rate":"50.00",
"active":"1"
}
Think that there are thousands of items like this.
But the problem is how can I trim the description value of this object automatically when running json_encode?
I dont wanna use "for each" because of performance i think.
Thanks...
use trim in array_map as :
$json = json_encode(array_map('trim',$array));

Twitter typeahead displays '&amp' instead of '&'

I'm trying to display search-results with the sign & in them. But when I render from php to json & converts to &amp.
Is there anyway I can prevent that, or before I print the names in the search-bar convert it back to &?
Thanks in advance!
EDIT:
HTML JS:
{
name: 'industries',
prefetch: 'industries_json.json',
header: '<h1><strong>Industries</strong></h1>',
template: '<p>{{value}}</p>',
engine: Hogan
},
industries_json.json (Created with json_encode)
[{"id":42535,"value":"AUTOMOBILES &AMP; COMPONENTS","type":"industries"}]
php-script which ouputs json:
public function renderJSON($data){
header('Content-type: application/json');
echo json_encode($data);
}
Use html_entity_decode function like...
Code Before:
public function renderJSON($data){
header('Content-type: application/json');
echo json_encode($data);
}
output: Gives html code in string like ex: appthemes & Vantage search Suggest
Code After:
public function renderJSON($data){
header('Content-type: application/json');
$data = json_encode($data);
echo html_entity_decode( $data );
}
output: Gives html code in string like ex: appthemes & Vantage search Suggest
The issue you're facing is HTML encoding. What you want is to decode the text before sending it to the client. It is important that you only decode the text properties of the JSON object (rather than the entire JSON object itself).
Here is a reference on HTML decoding in PHP: http://php.net/manual/en/function.html-entity-decode.php
I would do it in javascript. Once you have got the JSON, just use replace function of javascript on the JSON like this:
first convert it to string by this:
var jsonString=JSON.stringify(jsonData);
then replace &amp like this.
jsonString=jsonString("&amp","&");
then again, convert it to JSON obj;
jsonObj=JSON.parse(jsonString);
now, your JSON, will have & instead of &amp.
What's next ?
Do whatever you need to do with the jsonObj

strip_tags truncating JSON

I have a JSON Response like this:
{
"id":"2461",
"name":"GEORGIA INSTITUTE OF <leo_highlight style=border-bottom: 2px solid rgb(255, 255, 150); background-c",
"logo":"",
"address":null,
"city":null,
"state":null,
"campus_uri":"{{PATH}}2461\/"
},
....
....
When I do strip_tgs on this one, the whole JSON string is getting truncated at the name tag above. The JSON string looks like this.
{"id":"2461","name":"GEORGIA INSTITUTE OF
All below this line is gone. This is a huge JSON. But its getting truncated here.
Any ideas on what to do? I need to strip out all HTML tags.
Update:
Adding more details...
This JSON string I got is from encoding the query results array. So I get array from MySQL query and I encoded it with json_encode and trying to strip_tags on it.
$array = json_decode($json, true);
array_walk_recursive($array, function (&$val) { $val = strip_tags($val); });
$json = json_encode($json);
As simple... Decode it, walk through and encode it.
Strip out the tags after you have decoded the JSON object. You might do this in a lazy fashion (i.e. when needed) rather than go through every item an strip tags on all fields.

Categories