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

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

Related

Print json in pretty format using php code

I have array like below.
$resultArr = array();
$resultArr['status code'] = 200;
$resultArr['result'] = "Success";
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
return $json;
This is giving result like below
"{\n \"status code\": \"200\",\n \"result\": \"Success\",\n}"
without Pretty_print the result is like below
"{\"status code\":\"200\",\"result\":\"Success\"}"
I want response to be like this
{
"status code": 200,
"result": "Success"
}
Is something like this can be done pls, I am using PHP, Running the request in postman and the response are mentioned above
Note: I need to avoid using echo, because we are using code sniffers in project, so echo is not recommended.
You used JSON_PRETTY_PRINT for beautify output purpose,
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
If you want to use it as response remove that parameter,
$json = json_encode($resultArr);
Above line should work.
First of all, remove the JSON_PRETTY_PRINT flag.
Secondly, your problem is with the backslashes (\). These are escape characters. I don't know how you are printing your json or how you are viewing it.
If I do:
echo $json;
It outputs:
{"status code":200,"result":"Success"}
The backslashes are probably added because you're doing an AJAX request. In order to solve this, you could use jQueries .parseJSON() or add dataType: "json" to your ajax request.
And if you really don't want the backslashes to be added:
$json = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
Update
It might help to output using the following header:
header('Content-Type: application/json');
1. for Output Of API You Can Use Api:
header('Content-Type: application/json');
2. Using JSON_PRETTY_PRINT
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
3. You want To Display In Chrome
https://addons.mozilla.org/en-US/firefox/addon/json-handle/?src=recommended

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]

How to parse json with inline html?

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>"}

Geting XML form website

I try to get data from other website like this :
https://www.wowhead.com/item=65891&xml
I also have this php code:
$xml=file_get_contents('http://www.wowhead.com/item=65891&xml');
$xml= simplexml_load_string($xml);
var_dump($xml->item->name);
but it's not work.
This will give you an object of type SimpleXMLElement:
$xml->item->name
You can use its __toString() method to get the string content:
var_dump($xml->item->name->__toString());
To get the name text contents, use __toString() method:
var_dump($xml->item->name->__toString());
//output: string 'Vial of the Sands' (length=17)

make HTML tags inside json response work

I am retrieving some data from Wikipedia using Wikipedia API as JSON. I am getting html tags along with the data as response. When displaying on browser the html tags are displayed as plain text not as the regular output(I hope I am clear with this sentence). I want to show those as how it should look instead of plain text.following is my PHP code.
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Sachin_Tendulkar&format=json&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
echo $json ;
Following is the angularJS controller which is used to display the data
var demoApp = angular.module('demoApp',[]);
demoApp.controller('SimpleController',function ($scope,$http){
$http.post('server/view1.php').success(function(data){
$scope.info = data;
});
});
In this case:
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Sachin_Tendulkar&format=json&redirects&inprop=url&indexpageids';
$jsonString = file_get_contents( $url );
$jsonDecoded = json_decode($jsonString, true );
$pageData = $jsonDecoded['query']['pages'][57570]['extract'];
echo $pageData;
You need to use the function json_decode if you want to interpret JSON data.
You must use json_decode($json) to parse response to valid php code.

Categories