Having trouble while trying to send URL via JSON in PHP - php

I am working on web services of Android application in PHP. I am trying to send URL with other data in JSON. But the data sent by URL shows unwanted slashes (//) in the URL.
Here is the code I am using:
if(isset($_POST['category_id'])):
$result=$db->sub_category($_POST['category_id']);
if($result):
$msg="Success";
$arr = array();
while($row=mysql_fetch_array($result)):
$arr['response'][] = array('category' => $row['category'], 'image' => "http://intelmobizsolution.com/Iphone/upload/iphone/".$row['image'], 'msg'=>$msg,'status'=>true);
endwhile;
$abc=json_encode($arr);
echo json_encode($arr);
endif;
endif;
But the result shows like this:
{"response":[{"category":"Administrative Support2","image":"http:\/\/intelmobizsolution.com\/Iphone\/upload\/iphone\/27792582102banner_02.jpg","msg":"Success","status":true}]}
How can I send a URL with JSON in the format I want?

The best approach is to accept the slashes. They do absolutely not harm. It is perfectly acceptable to have them escaped in JSON strings.
If you really want to get rid of them, then you can use:
json_encode($arr, JSON_UNESCAPED_SLASHES);
… but if your data ever includes the string </script> and you output the JSON into some JavaScript in an HTML document, then you'll break your script.

In PHP > 5.4 you can use
json_encode($arr, JSON_UNESCAPED_SLASHES);
http://php.net/manual/en/function.json-encode.php

Related

Json encode PRETTY PRINT printing out with slashes in php

I've followed all the tutorials on printing out a nicely formatted JSON response, but I can't get it to work. If I don't do json_encode PRETTY PRINT, it prints out as a raw JSON result in a single line,
But when I do add all that, it still prints it out as a single line, but with slashes before every quotation mark.
Heres the code I'm using
echo"<pre>";
$response = wp_remote_get( 'URL TO JSON DATA' ));
$jsonData = json_encode($response['body'], JSON_PRETTY_PRINT);
header('Content-Type: application/json');
echo $jsonData;
echo"</pre>";
And heres a sample of the data being printed out
"{\"head\": {\"error\": \"\", \"version\": \"
I can provide real data if necessary, I just wanted to show what I meant by a slash before every quotation, I'm hoping that's enough to give an idea of my problem
Thanks!
The data you get from wp_remote_get is already a perfectly encoded JSON string, no need to encode again.
When you encode again, PHP generates a structure with one element, the string you originally get, and escapes all the quotes to form valid JSON.
So you can output the data directly :
$response = wp_remote_get( 'URL TO JSON DATA' ));
header('Content-Type: application/json');
echo $response;

How to parse JSON passing in PHP web service

I want to pass a JSON: {"name":"jason","age":"20} in PHP though POST
In RoR, I can get the two values by using params["name"] & params["age"]
But I don't know how to get them in PHP.
I understand that I can 'translate' the JSON string into associative array by using json_decode but I don't know how to get the JSON string.
In my PHP code, I has tried something like this:
<?php
$json_string = $_POST['params'];
$json_object= json_decode($json_string);
print_r($json_object);
echo $json_object->name;
echo " ";
echo $json_object->age;
?>
Then I has tested the PHP with terminal and I got the correct result
curl -d 'params={"name":"jason", "age":"20"}' xxxx/test_json_decode.php
It works but it seems strange to me, because I didn't set the 'Content-Type: application/json'
Is it the correct way to parse JSON in PHP?
The content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. A json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again.
As long as what you pass into json_decode() is a valid JSON string, regardless of the mime-type it was sent with, it'll be decoded into a native structure.

Beginner to creating and reading JSON objects

Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual

Why is json_encode adding backslashes?

I've been using json_encode for a long time, and I've not had any problems so far.
Now I'm working with a upload script and I try to return some JSON data after file upload.
I have the following code:
print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON
This gives me the following results:
// print_r result
Array
(
[logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg
[img_id] => 54
[feedback] => Array
(
[message] => File uploaded
[success] => 1
)
)
// Echo result
{"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}
Can anyone tell me why json_encode adds slashes?
update
#Quentin said that something is happening between json_encode and .parseJSON and he's right.
Doing a alert(data.toSource()); gives me the dollowing result:
({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200})
And this is not valid JSON. It also adds the status:200 and I have no idea where this comes from.
Could it be that the Plupload bind does something to my returned data?
This is my js script:
uploader.bind('FileUploaded', function(up, file, data) {
alert(data.toSource());
$('#' + file.id + " b").html("100%");
});
Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).
json_encode($array,JSON_UNESCAPED_SLASHES);
I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.
Here is what was happening. If you do:
$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);
The result is:
["{\"test\":\"2\"}","{\"test\":\"four\"}"]
So, what you actually need to do is:
$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);
And this will return
[{"test":"2"},{"test":"four"}]
Can anyone tell me why json_encode adds slashes?
Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.
Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.
It doesn't. In JSON "/" and "\/" are equivalent.
The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.
This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).
Suppose your data was : He said "This is how it is done".
Then the actual data should look like "He said \"This is how it is done\".".
This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.
This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.
Try this
$arr = ['This is a sample','This is also a "sample"'];
echo json_encode($arr);
OUTPUT:
["This is a sample","This is also a \"sample\""]
Make sure your php script has the right header or it will add the slashes
header('Content-Type: application/json');
I had a very similar problem, I had an array ready to be posted. in my post function I had this:
json = JSON.stringfy(json);
the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json) in every validation and realized that the json was treated as a string instead of an object.
In conclution i shouldn't have assinged json = JSON.stringfy(json) instead i assigned it to another variable.
var aux = JSON.stringfy(json);
This way i keep json as an object, and not a string.
json_encode will always add slashes.
Check some examples on the manual HERE
This is because if there are some characters which needs to escaped then they will create problem.
To use the json please Parse your json to ensure that the slashes are removed
Well whether or not you remove slashesthe json will be parsed without any problem by eval.
<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>
This is my code and i m able to parse the JSON.
Check your code May be you are missing something while parsing the JSON

Sending HTML Code Through JSON

I've got a php script which generates HTML content. Is there a way to send back that HTML content through JSON to my webpage from the php script?
Yes, you can use json_encode to take your HTML string and escape it as necessary to be valid JSON (it'll also do things that are unnecessary, sadly, unless you use flags to prevent it). For instance, if your original string is:
<p class="special">content</p>
...json_encode will produce this:
"<p class=\"special\">content<\/p>"
You'll notice it has an unnecessary backslash before the / near the end. You can use the JSON_UNESCAPED_SLASHES flag to prevent the unnecessary backslashes. json_encode(theString, JSON_UNESCAPED_SLASHES); produces:
"<p class=\"special\">content</p>"
Do Like this
1st put all your HTML content to array, then do json_encode
$html_content="<p>hello this is sample text";
$json_array=array(
'content'=>50,
'html_content'=>$html_content
);
echo json_encode($json_array);
All string data must be UTF-8 encoded.
$out = array(
'render' => utf8_encode($renderOutput),
'text' => utf8_encode($textOutput)
);
$out = json_encode($out);
die($out);
In PHP:
$data = "<html>....";
exit(json_encode($data));
Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/
You can send it as a String, why not. But you are probably missusing JSON here a bit since as far as I understand the point is to send just the data needed and wrap them into HTML on the client.
Just to expand on #T.J. Crowder's answer.
json_encode does well with simple html strings, in my experience however json_encode often becomes confused by, (or it becomes quite difficult to properly escape) longer complex nested html mixed with php. Two options to consider if you are in this position are: encoding/decoding the markup first with something like [base64_encode][1]/ decode (quite a bit of a performance hit), or (and perhaps preferably) be more selective in what you are passing via json, and generate the necessary markup on the client side instead.
All these answers didn't work for me.
But this one did:
json_encode($array, JSON_HEX_QUOT | JSON_HEX_TAG);
Thanks to this answer.

Categories