-2

I am trying to Get JSON data using PHP from another page, but its showing up in a weird formation and beside eachother on a single line.

I tried to use json_decode method, but didnt work for me! But how can I make it show up in the correct formation showen below:

This is how I want it to show up, which it does on the Main Page:

{
    "games": "pacman",
    "level":"2",
    "icon":"LINK HERE",
    "topscorer":"3134000",
    "nextlevel":"3",
    "players":[ 21322,
                43131,
                84993,
                8212,
                501421,
                7832126 ]
}

And this is what I get:

{ "games": "pacman", "level":"2", "icon": "LINK HERE", "topscorer": "3134000", "nextlevel": "3", "players": [ 21322, 43171, 84993, 8222, 501421, 7832126 ] }

My PHP Code:

<?php
$page = file_get_contents('WEBSITE-URL-HERE');
echo $page;
?>

Is there any way to make it show up in correct formation just like the one above? Any answer could be help full in this case. Thank you

  • 2
    Look at the `JSON_PRETTY_PRINT` option for [json_encode](http://php.net/json_encode). – Vatev Nov 29 '13 at 18:12
  • @Mate, Yes I know they are Equal. I am using it for a NET project to get the content using NET. The problem is that I am not able to get the content with the Formation I get.. – Josh Aknard Nov 29 '13 at 18:13
  • http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php – Mate Nov 29 '13 at 18:15
  • If your parser can only parse pretty printed JSON you really need to get another one. – Vatev Nov 29 '13 at 18:17
  • 1
    @Mate, Very helpfull links! Thank you! Im gonna take a look! – Josh Aknard Nov 29 '13 at 18:22
  • try `print_r(json_decode($page));` – Pranav C Balan Nov 29 '13 at 18:22
  • First of all, I think you are mistaking "formation" with "format", please let it be format from now on. Next, **why** do you need your JSON formatted like so. Is it for human readers? for debugging purposes? unluckily, `JSON_PRETTY_PRINT` is not available in `PHP < 5.4.0` – hanzo2001 Nov 29 '13 at 18:24
  • 1
    @Pranav C, I get all lots of Arrays and Numbers on the same line still! But very helpfull too! I can probably do something with it.. Thank you – Josh Aknard Nov 29 '13 at 18:24
  • @Vatev, Thank you ! I did take a look at JSON_PRETTY_PRINT all day, but I was lost at the end! The problem is that I am trying to get it from another page. Else the Pretty Print would work if it was used to Parse my own content. – Josh Aknard Nov 29 '13 at 18:27
  • 1
    Why do you care what the format is? Is you are just trying to read JSON data into your PHP code and use it ins some manner, the format shojuld not make a bit of difference. – Mike Brant Nov 29 '13 at 18:41
  • josh what's the problem, you trying to parse json? you getting the same json its just not indented the same way – meda Nov 29 '13 at 18:49
  • @Mike Brant, you shouldnt be answering in cruel way! Nobody asked you! Try calm down! I am a new member on here. – Josh Aknard Nov 29 '13 at 19:11
  • I don't think Mike meant to be "cruel"; replace "care" with "mind" and remove "bit of", and the question remains valid. This is valid JSON data, but formatted with different whitespace. [`json_decode()`](http://php.net/json_decode), or any other JSON parser, should cope with it fine. – IMSoP Nov 29 '13 at 19:15
  • @JoshAknard It's not cruel. I seriously want to understand why yo would care. JSON is really nothing but a serialization format meant to be read by code. If you want to present a friendly way for display data from data passed via JSON, I would think you could actually encode the object and present data in a nicer format than a JSON pretty format. If you just want this for debugging, then simply take teh echoed result and put it into JSONlint or something. – Mike Brant Nov 29 '13 at 19:16
  • @Mike-Brant, I explained above that I am using VBNET to get the content from the parsed JSON page that I am creating right now! And the problem is that I can only get the content if its showen correctly, and not the way I get it now! So its not about the JSON at the end, but about my project as a Programmer to get the content correctly and without delays... – Josh Aknard Nov 29 '13 at 19:25
  • @IMSoP, It could def be asked in a better way as mr Mike did the 2nd time. – Josh Aknard Nov 29 '13 at 19:27
  • 1
    So, you have a tool in VB.NET that is failing if given JSON which is not "pretty printed" (meaning, with extra spaces and new lines added)? That sounds like a problem with that tool, not with the JSON; you need to look for a better tool to parse the JSON with, as no JSON parser should be failing on either of the examples you've shown us. – IMSoP Nov 29 '13 at 19:44
  • @JoshAknard I agree with IMSoP comment above. The reason why ask these questions in these comments is that it sounds like you are trying to solve a problem that doesn't need to be solved. Any solid JSON parser should be able to work with JSON whether it be formatted in a compact manner or whether it is formatted with line breaks and other whitespace as would be in a user-friendly format. – Mike Brant Nov 29 '13 at 19:47
  • IMSoP got the answer below! @Thank guys, and MikeBrant you but I would've liked to see a correct answer from you than replies that were really a waste.. – Josh Aknard Dec 01 '13 at 17:04
  • @JoshAknard Check out the help page on [What should I do when someone answers my question?](http://stackoverflow.com/help/someone-answers). You can "accept" an answer by clicking the tick next to it. The big take-home here though is to think carefully about and explain what your real problem is, so that people can think of answers outside of your current line of thinking. – IMSoP Dec 01 '13 at 17:46

3 Answers3

0

I know this is kinda crude and I haven't tested it but it was done fast

a standalone test file

Leave this by itself as a test to see the output

<?php

function prettifyJSON($json) {
  static $i = 0;
  if (is_bool($json)) return $json ? 'true' : 'false';
  if (is_null($json)) return 'null';
  if (is_numerical($json)) return $json;
  if (is_string($json)) return '"'.$json.'"';
  if (is_array($json)) {
    $r = array();
    foreach ($json as $v) $r[] = prettifyJSON($v);
    return '['.implode(', ',$r).']';
  }
  if (is_object($json)) {
    $r = array();
    foreach ($json as $k => $v) $r[] = '"'.$k.'": '.prettifyJSON($v).PHP_EOL;
    return '{'.PHP_EOL.implode(', ',$r).'}'.PHP_EOL;
  }
}
ob_start();
echo 'this script is intended for testing purposes';

// assume this is a text file with parsed json in it
$page = file_get_contents('WEBSITE-URL-HERE');

// let's look at it raw
echo 'RAW OUTPUT: '.PHP_EOL;
var_dump($page);

echo 'FORMATTED OUTPUT: '.PHP_EOL;
echo prettifyJSON(json_decode($page));

echo PHP_EOL.'done formatting';
echo '<pre>'.ob_get_clean().'</pre>';
exit;

Please give some feedback and I'll update this to suit your needs

hanzo2001
  • 1,338
  • 1
  • 10
  • 24
  • Thank you very much for your efforts! I am getting a Blank Page! I tried with 2 different Servers I tested it on my Linux Godaddy (Shared), and my Private Centos Cloud! Still a Blank Page! I will def give more feed back after more testing! Thats for sure! – Josh Aknard Nov 29 '13 at 18:43
  • I made some edits but this is a test file, only use it to test if the function `prettifyJSON()` works as intended. If you still get a blank page with nothing on it after running something as simple as this then we have an environment issue in the background – hanzo2001 Nov 29 '13 at 18:59
  • Wow.... This time I got the content but Still on a single Line... Only the last 3 Lines were appearing below each.. >> FORMATTED UTPUT: null done formatting....... I would love to share the link, but since its a product that we havnt released yet I cannnot share the data link directly. Thank you very much! I will be trying... – Josh Aknard Nov 29 '13 at 19:03
  • ok, I made a mistake in my code, I hope it works now. I also added the `
    ` tags because it seems I can't force the mimetype to be plain text. Please tell me that there is a bunch of garbage outputted now
    – hanzo2001 Nov 29 '13 at 19:09
  • This time I got, 2 lines. The first line splits from the text "players:" and the 2nd line looks to be fixed with the screen and contains rest of the content! I dont know why I keep getting the same thing :(. Thank you very much Hanoz, I really appereciate your time and efforts helping out! – Josh Aknard Nov 29 '13 at 19:21
  • We'll I'm out of ideas T_T – hanzo2001 Nov 29 '13 at 19:26
  • You did amazing! Your help was a big thing for me to learn! I have saved your Methods for later use! So your help was pretty informative! I thank you from the bottom of my heart! – Josh Aknard Nov 29 '13 at 19:32
0

The first format is probably just the plain text format. The second one is how it looks when rendered by a browser (browsers don't render new-line characters). If you want it to look like in the first sample, wrap the output in <pre> tags:

<pre>
<?php echo file_get_contents('WEBSITE-URL-HERE'); ?>
</pre>
laurent
  • 88,262
  • 77
  • 290
  • 428
0

It's just occurred to me that this is absolutely certain to be an X/Y Problem (you are asking a question based on your attempted solution rather than the original problem).

From what you have told us the actual problem could be summarised like this:

I have some code written in VB.NET which fetches JSON data. When I fetch the data from (undisclosed source) it works fine, but when I fetch it from PHP, it fails (in some unspecified way).

You have then looked at the difference, and seen that when you look at the two URLs in a browser, they appear to be formatted differently, and then assumed that this is the cause of your problem.

To test whether whitespace really is the problem should be easy: create 2 PHP files with the following content, and point your VB.NET code at each:

test_1.php

<?php
echo '{
    "games": "pacman",
    "level":"2",
    "icon":"LINK HERE",
    "topscorer":"3134000",
    "nextlevel":"3",
    "players":[ 21322,
                43131,
                84993,
                8212,
                501421,
                7832126 ]
}';

test_2.php

<?php
echo '{ "games": "pacman", "level":"2", "icon": "LINK HERE", "topscorer": "3134000", "nextlevel": "3", "players": [ 21322, 43171, 84993, 8222, 501421, 7832126 ] }';

If test_1.php works, but test_2.php doesn't, then whitespace really is your problem. However, since both should be valid JSON, your problem must then lie in your VB.NET code - so you don't need to worry about why the two look different.

If - as I strongly suspect - both tests fail, then you need to look for some other problem. The two most likely are HTTP headers and URL access / security.

HTTP headers are sent by a web server alongside the content, and tell the browser - or, in this case, your VB.NET code - how to process that content. The most likely one to be relevant here is the Content-Type header. By default, PHP will advertise any content it generates as text/html, which isn't what you want. The official content type for JSON data is application/json, and you can tell PHP to set the appropriate header with the header() function, as follows:

<?php
header('Content-Type: application/json');
echo '{ "games": "pacman", "level":"2", "icon": "LINK HERE", "topscorer": "3134000", "nextlevel": "3", "players": [ 21322, 43171, 84993, 8222, 501421, 7832126 ] }';

The other possible problem is access to the URL itself: you may be able to access your PHP page in a browser, but your VB.NET code may not. You may have put the PHP script up on a server which is not visible from the rest of the Internet, because it is local to your network, or behind a firewall. Alternatively, there may be security restrictions on which URLs can be loaded by the VB.NET code, or a firewall blocking the server where that code is running.

This is trickier to test without knowing how your VB.NET code works, but if you just fetch the content of the URL in VB.NET without trying to process it in any way, you may be able to work out which URLs work and which don't.

Community
  • 1
  • 1
IMSoP
  • 89,526
  • 13
  • 117
  • 169
  • I think that worked with the header method you explained above! I used the "header" method! I will be keep testing a few more times, and with the other links I got as well. Hope that it will work out with all of them. So far so good. Thank you IMSoP! – Josh Aknard Dec 01 '13 at 22:20