0

This might seem like a dumb question but after a long search, I'm stumped.

I'm using a query to retrieve data then encoding to JSON for use in various places around my site. There's just one issue. I can't seem to retrieve the data!

Query (data.users.php):

$arr = array();

$rs = mysql_query("SELECT
    CONCAT(m.firstName,' ',m.lastName) AS name,
    m.email,
    m.permission,
    m.costRate,
    m.dt,
    m.memberID,
    m.moduleFinancial,
    o.orgName

    FROM members m

    LEFT JOIN organisations o ON m.organisationID = o.organisationID
    WHERE status = 'true'
    ORDER BY name"
) or die(mysql_error());

while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
header("Content-type: application/json");

    echo json_encode($arr);

Example of the data:

[{"name":"Admin User","email":"[email protected]","permission":"admin","dt":"2013-02-02 10:26:29","memberID":"M0000001"},{"name":"Another User","email":"[email protected]","permission":"admin","dt":"2012-02-02 10:26:29","memberID":"M0000002"}]

Any ideas?

Updated fetch code:

ob_start();
            include("../data/data.users.php");
            $arr = json_decode(ob_get_clean(), true);

            foreach($arr as $item) {
                if ($item['memberID'] == $_GET["ID"]) {
                    $user_name = $item['name'];
                }
            }
4
  • Yes, that is normal - JSON is supposed to have a lack of whitespace in order to be as compact as possible. Commented Feb 19, 2013 at 8:38
  • In that case, any idea what's the matter with the code that displays the data? Commented Feb 19, 2013 at 8:53
  • I think @fab has got it with his answer below. Commented Feb 19, 2013 at 9:40
  • Hey guys, please see the edited question. I've added additional detail. Commented Feb 21, 2013 at 9:17

4 Answers 4

2

PHP >= 5.4 has JSON_PRETTY_PRINT option as documented here: http://php.net/manual/en/function.json-encode.php to get nicely formatted JSON string:

json_encode($arr, JSON_PRETTY_PRINT);
Sign up to request clarification or add additional context in comments.

Comments

1

Try this dear....

Input

{"key1":[1,2,3],"key2":"value"}

Output

    {
    "key1": [
        1,
        2,
        3
    ],
    "key2": "value"
}

Function Code :

    function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $prev_char = '';
    $in_quotes = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if( $char === '"' && $prev_char != '\\' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
        $prev_char = $char;
    }

    return $result;
}

may this helps to you........

Comments

1

I believe, your problem lies somewhere else, json_decode does not need line breaks. However, I found this line suspicious:

json_decode(file_get_contents("../data/data.users.php"),true);

you want to read a PHP script as JSON? This is source code, nothing gets executed there!

Update:

It's exactly like I suspected: you read the PHP file and pass it to json_decode. The PHP source code is not valid JSON, thus it returns null. file_get_contents would only be possible with the http wrapper:

file_get_contents("http://example.com/data/data.users.php")

but that's unnecessary complicated and generally not a good idea. Also, the script would have to be under the public web directory. You should include data.users.php. For this, you have two options:

  1. change echo to return and then use:

    $arr = json_decode(include("../data/data.users.php"), true);
    
  2. use output buffering:

    ob_start();
    include("../data/data.users.php");
    $arr = json_decode(ob_get_clean(), true);
    

The first option should be the preferred one, however, if you cannot change data.users.php for some reason, the second one is a valid workaround.

P.S.: you might want to get rid of the call to header() too, if data.users.php will not be called directly over the web. Otherwise, remember to override the content-type header in your second script if it does not deliver JSON to the browser/client.

5 Comments

Additional detail added above.
Thanks Fab, it's working on a test page. Phew! Just one more problem. When I add the code to the actual page the include breaks the page. I've added the amended code above.
What do you mean with "break"? Did you read my note about header('Content-type:...')?
Unfortunately I need the header to allow the data to be read by Kendo UI which is running in other areas of the site. When I say 'not working' I mean that when I call the page this code lives on, nothing displays. Remove the include or more the code below some text (for instance), the text displays just fine. Thanks for your help BTW. It's people like you that drive this place!
There could be different reasons, but you should try to remove the header call, just to see if it makes a difference. If so, make sure that nothing gets outputted before the include and call header('Content-type:text/html;charset=utf-8);` (or whatever you need) after it, to override the JSON header. Also, enable error_reporting for development! A blank page usually means an error, if you allow PHP to display or log it, you will be wiser ;)
0
echo json_encode($arr)."\r\n";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.