why isnt json file separating the records (PHP) [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pretty-Printing JSON with PHP
I'm working on a script that creates a JSON file. Right now I'm just using json_encode (PHP 5.2.x) to encode an array into JSON output. Then I print the returned value to a file and save it. Problem is that the client wants to be able to open these JSON files for readability, so I'd like to add line breaks in and "pretty print" the JSON output. Any ideas on how to do this? My only other alternative that I can see is to not use json_encode at all and just write the file contents manually and add in my own line breaks for each line.
Here's what I get:
{"product_name":"prod1","val1":1,"val2":8}
Here's what I want:
{
"product_name":"prod1",
"val1":1,
"val2":8
}
I suppose I could also just replace every comma with a command followed by a \n, and same for the brackets... Thoughts?

PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).
This should do the job:
$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);
See http://www.php.net/manual/en/function.json-encode.php
Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);
But if you really want to prettify your json... Check this out

Here's a function to pretty up your json:
pretty_json

Related

JSON pretty print without use json_decode in php

For example i have json strings like this ( from the first place ). And It's not formatted.
{"data":[{"id":"14","memo_kondisi":"Kekurangan
pekerjaan","total_row":"5","nilai_temuan":"1.000.000","data_sebab":[{"id":"15","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[{"id":"25","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"26","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"31","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"}]},{"id":"16","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[{"id":"34","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"35","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"}]}]},{"id":"15","memo_kondisi":"Kekurangan
pekerjaan","total_row":"2","nilai_temuan":"1.000.000","data_sebab":[{"id":"5","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]},{"id":"10","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]}]},{"id":"16","memo_kondisi":"","total_row":"2","nilai_temuan":"0","data_sebab":[{"id":"9","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]},{"id":"12","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]}]}]}
I see some similar question that you have to use json_decode and i have to encode again and using json_encode($json,JSON_PRETTY_PRINT)
Is there a way for make json readable without decode the JSON first and encode it again in PHP ?
Note : I expect the result is still in JSON
Not really. Using someone else's parser lib won't make any difference, as they'll call json_decode() too.
You could create a little function that you could call:
function prettify($json)
{
$array = json_decode($json, true);
$json = json_encode($array, JSON_PRETTY_PRINT);
return $json;
}
Then echo prettify($jsonString); would be easier than constantly decoding and re-encoding. See here https://3v4l.org/CcJlf
Only a parser can understand the JSON, so you can either do what you proposed or write your own parser. If you have access to the origin of the JSON, make it pretty in the first place.

How to print Array READABLE [duplicate]

This question already has answers here:
Is there a pretty print for PHP?
(31 answers)
Closed 7 months ago.
How do i print an Array readable? print_r($array); and var_dump($array); both produce some very ugly clutter of that $array. Ok it is what it says, it prints that array, but i'd like to have some well formated print of that array, how do i do that?
echo '<pre>';
var_dump($array);
echo '</pre>';
Or to a better yet performance, use xDebug with
html_colors = on.
html_colors can be found on php.ini file.
xdebug is from http://xdebug.org/download.php
With xDebug and Colors you don't need to use
echo '<pre>';
echo '</pre>';
it's beautiful as-is.
Actually, it is well-formatted but HTML ignores line breaks and double spaces.
You just have to view the page's source code (CTRL+U or right-click > view source code)
You can wrap your var_dump() output in <pre> to preserve the monospacing:
echo "<pre>" . var_dump($array) . "</pre>";
echo "<pre>".print_r($array, true)."</pre>";
try this code
$myArray=array("a","b","c");
foreach($myArray as $A)
{
echo $A."<br/>"; // you can use any style here like table, div span etc...
}
I like:
highlight_string(var_export($array, true));
var_export() is usable (copy/paste) PHP code as well.
if you want to see it well formatted, you can encode it to json object and print it pretty :)
You have to do is:
echo json_encode($array,JSON_PRETTY_PRINT); //This needs PHP 5.3 at least.

Read json data from Android with php

I'm trying to read data from a decompiled application of Android with a php server. I used wireshark to understand what types of data the application sends, and the result is:
{"initType":"first time","parameters":true,"details":................}
I trying to capture this data and insert them in a file with this php code:
<?php
$json = $_POST["initType"];
$decoded = json_decode($json, TRUE);
if ($decoded === FALSE) {
throw new Exception('Bad JSON format.');
}
$file_handle = fopen('tmp.json', 'w');
fwrite($file_handle, $decoded);
fclose($file_handle);
?>
The file is correctly generated but it's empty. What is the error?
Because $decoded is an array, use a loop to write it to file or write the encoded JSON to file ($json). Try using this:
fwrite('tmp.json', print_r($decoded, TRUE));
or:
file_put_contents('tmp.json', print_r($decoded, TRUE));
Update (per your comments):
If you run a print_r($decoded) and it prints nothing, there is a problem with the decoding process of the JSON object passed in. I would recommend checking this to make sure it is formatted correctly. JSON formatting is a strict business and will halt your end goal if you are missing a double-quote or bracket. Start by echoing out $json ($_POST["initType"]) and compare the format to examples posted online (just Google "json formatting"). I can tell you that one thing that stands out to me is: "parameters":true (from your example above). I have a strong suspicion that the key true should be in double quotes. If you are positive that the JSON variable is correct syntactically, I don't think I would be of any more help. Using json_decode() to produce an array to very straight forward once you get it right.
Don't decode the json at all -this only brings the problem of trying to serialize an array that burmat mentioned in his answer.
Write to the file the json content straight away:
fwrite($file_handle, $json);
Also, though I am not PHP expert it seems you access the body of the post request wrongly. Please refer to the following post.

Sorting out raw data from an API link in PHP that is in JSON format

Hopefully this will be quite an easy one for you here.
Anyway, I have been having alot of trouble with fread() so have decided to use an api link that I have been able to locate.
The script is simply to convert extracted game server data into a readable format.
The link for the "Serialized" data is : http://api.typefish.co.uk/monitor/sa-mp/80.86.81.14:6969/?info&masterlist&rules&players
Simply put I have very little in the way of ideas on what I can do with this data.
So far this is what I have although I am probably miles off:
$content = file_get_contents("http://api.typefish.co.uk/monitor/sa-mp/80.86.81.14:6969/?info&masterlist&rules&players");
trim($content, "{");
trim($content, "}");
foreach(exlpode(",", $content) as $pieces){
explode(":", $pieces);
}
And now I am stuck. Can someone either tell me a way thats miles better or help me finish off the script with some ideas?
Thanks
This is the code I have now after 2 answers:
$newarray = json_decode($content);
var_dump($newarray);
echo "<br><br>";
echo $newarray->{"mapname"};
The problem is that I am unable to display the variable in this format, how can I rebuild that so I can view the variables.
I have changed this:
echo $newarray->{"mapname"};
to this:
echo $newarray->data->rules->mapname;
This data is in json format. All you need to use to convert it into a php Array is json_decode($content)
Reference: http://us3.php.net/json_decode
And read more about json here: http://www.json.org/
You ar doing it wrong, it's not PHP serialized string, its json output you can use json_decode to get string into PHP array.
Like:
var_dump(json_decode($content, true));

PHP json_encode not returning valid json

I am running a Debian box with PHP v5.2.17. I am trying to get around the cross-domain issue with an XML file and am using this got to fetch any xml and return json:
<?php
header('content-type: application/json; charset=utf-8');
if( strlen($_GET["feed"]) >= 13 ) {
$xml = file_get_contents(urldecode($_GET["feed"]));
if($xml) {
$data = #simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($data);
echo isset($_GET["callback"]) ? "{$_GET[’callback’]}($json)" : $json;
}
}
?>
The problem is, its not returning valid json to jquery.. The start character is "(" and the end is ")" where jquery wants "[" as the start and "]" as the end. I've taken the output and used several online validation tools to check it..
Is there a way I can change these characters prior to sending back or pass json_encode options?
You could change json_encode($data) to json_encode(array($data)) if it expects an array (like you're saying):
$json = json_encode(array($data));
EDIT: Also, I believe the SimpleXml call will result in a bunch of SimpleXmlElements, perhaps json_encode then thinks it should be objects, instead of arrays? Perhaps casting to an array will yield the correct results.
You cannot json_encode() SimpleXMLElements (that's the type that is returned by simplexml_load_string(). You have to convert the data from the XML file into some native PHP type (most likely an array).
SORRY that's wrong. json_encode() can in fact encode SimpleXMLElements (at least on my PHP version 5.3.4). So if your client-side code expects an array you must wrap your $data in an array:
$json = json_encode(array($data));
We can use json_encode() function most probably on array. so you first take XML content into PHP array and then apply json_encode().I think this will solve your problem..
It seems that you are sending an empty callback parameter or something, but the callback parameter in jQuery must look exactly like this: callback=?

Categories