Send xml string in json object using php slim - php

I have written a REST Api using slim framework 3, and returning response in JSON like this,
return $response->withHeader(
'Content-type',
'application/json; charset=utf-8'
)->withJson($data, 200);
which is working fine.
$xml = '<?xml version="1.0" encoding="UTF-8"?><dialog createdBy=""createDate=""><dialog>' // looks like this
$data = [
'name' => 'xmlName',
'xml' => $xml // fetching from db
]
Now, I have xml string stored in database and want to send it to the client end, I have to save that xml string as in another database as it is.
But when I encode xml string, my json gets break.
I have also tried like,
json_encode($data, JSON_HEX_TAG);
which converts my xml to.
"\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?\u003E\n\u003Cdialog createdBy=\"\"
How can I correctly encode the xml in JSON and then get back the original xml string as it is?
Your feedback is much appreciated.

If you look at the withJson() source code you'll see that all it does with data is processing it with json_encode()—nothing special on the Slim side. In fact, your XML is just fine: \u003C and \u003E are the entities for < and >. Remember that JSON is a data format for computers, not people!
Additionally, the JSON spec states that you need to have a top level object or array. So you can't just send a string back to the client and expect it to be processed as JSON because it will not be JSON. If json_encode() does not just crash it's because it has been designed to encode partial JSON since it's a useful feature some times. You absolutely need to design a valid JSON structure, e.g.:
->withJson(array($xml), 200)

Actually I just found my answer by the hint of htmlentities #Álvaro González gave.
I just converted my xml string like,
[
'name' => 'xmlName',
'xml' => htmlentities($xml)
]
I am able to receive the xml string as it is without any json break.

Related

php: json_decode containing HTML fails to decode

I need to use a customer's API for loading JSON which only contains something like:
{"html" : "foo"}
The API is being used from other services so I'm pretty sure it's valid.
However, when trying to decode it using json_decode i'm always getting an empty string which means it's not valid. I found out i need to "fix" the JSON-String by replacing:
$json = str_replace("\\>", "\\\\>", $json); // \> = invalid json
It works mainly on each request but not on certain others but it's very tricky to debug and i can't imagine that replacing is the proper method.
How would i do it the easy way for converting the json string into a valid one?
thanks
Ok i could find out what's wrong:
The HTML contains backslashes in the closing tags, for example <br\>
You need to replace them like this:
$json = str_replace("\\>", "\\\\>", $json);
and json_decode will work

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

Passing angled bracket in hex via JSON AJAX from PHP to JS

My system runs some MySQL queries in PHP to retrieve data. The data that is retrieved is structured in an array similar to below:
$ret = array(
"name" => "John Doe",
"location" => "Antarctica",
"description" => "Height < 200"
);
I return this through AJAX via:
echo json_encode($ret);
The AJAX error event is fired and upon inspection of the returned data (jqXHR.responseText) via Chrome console, I'm noticing:
"description" : "Height \x3c 200"
which is throwing a parse error.
I know that \x3c is the hex representation of "<" and apparently, that form renders the JSON invalid. I can't seem to find a way to make it such that I'm able to pass the angled bracket via JSON in a valid form. Direct string replace of "\x3c" on the PHP side doesn't work.
Further, I know that specifying the AJAX return as HTML will work, but I'm passing a set of data hence the use of JSON.
Try this:
echo json_encode( $ret, JSON_HEX_TAG );
Use json_last_error() to debug.
http://www.php.net/manual/en/function.json-decode.php
Using the native Chrome JSON object (window.JSON), i am able to parse the output from you php program no problem,
"description" : "Height \x3c 200"
and am able to serialize that into a javascript JSON object.
var jsonString = JSON.stringify({"description": "Height \x3c 200"});
//jsonString has the value "{"description":"Height < 200"}"
var jsonObject = JSON.parse(jsonString);
//jsonObject has an object that looks like this
//Object
//description: "Height < 200"
//__proto__: Object
if you need compatibility with browsers that don't support a native JSON object, i would recommend using a library such as JQuery.
Additionally, the json_encode() function in PHP can be passed a configuration object to customize exactly how your JSON is encoded, if you don't like the '\x3c', you can change it to something your javascript parser may like better like '&lg;' :)
http://php.net/manual/en/function.json-encode.php

How to parse json (feed) from PHP

I have a json feed from zoho : here, you can acces the same file unencrypted here
I like to be able to display and parse the data from that feed int html
I have ask a similar question yesterday, but the solution was a javascript, and having java disable client side can lead to nothing to display... so i will go with php. I can parse a var but a feed ?....
Question #2. Is it possible to capture a json feed, and save it as file (for backup purpose), so i will acces that file if the site go down (small possibilites)
You first have to get the JSON data from the remote server ; not sure how you can do that, considering there seems to be an authentication mecanism in place, but maybe file_get_contents or curl could help.
Once you have that JSON string in a PHP variable, it's just a matter of calling json_decode on it, to get your data.
For instance :
$json = file_get_contents('http://produits-lemieux.com/json.txt');
// you can save $json to a file, if needed :
//file_put_contents('file/path/my-file.txt', $json);
$data = json_decode($json);
var_dump($data);
Will get you an output like this one :
object(stdClass)[1]
public 'Liste_des_produits1' =>
array
0 =>
object(stdClass)[2]
public 'Added_Time' => string '28-Sep-2009 16:35:03' (length=20)
public 'prod_ingredient' => string 'sgsdgds' (length=7)
public 'prod_danger' =>
array
0 => string 'sans danger pour xyz' (length=20)
....
Note I used the "not encrypted" version, because I have no idea what kind of API you need to use to access the crypted one (never used "zoho")
json_decode will convert the json string to object form by default, in order to use it as associative array you have to specify 'true' as second parameter, example below.
json_decode($json,true)
reference : php Json_decode reference
The simplified code to do what you want.
$sJson = file_get_contents('http://example.com/path/to/feed.json');
file_put_contents('/path/to/file', $sJson);
$oJson = json_decode($sJson);
var_dump($oJson);
If URL Wrappers are off or you need authentication headers (or other special headers set), use the curl libraries in place of file_get_contents.
I like to be able to print/access some variable but cannot seem to have the trick to access the array the wright way
based on the previous answer :
$json = file_get_contents('http://produits-lemieux.com/json.txt');
$data = json_decode($json);
//var_dump($data);
print_r($data['prod_ingredient']); //dont work !... error
print_r($data['Liste_des_produits1'].prod_ingredient[0]); //dont work !... error

Categories