开发者

PHP script that writes JSON code to txt file has missing spaces and line breaks. How to fix?

I'm trying to create a PHP script that will "write" to a txt file in valid JSON format.

The script I've created basically works, except for some reason, the JSON code written to the txt file has no spaces or line breaks (it's just one big long line).

I've checked the JSON code (from the txt file) at http://jsonlint.com/ and http://www.jslint.com/.

JSON Lint says the txt file JSON code is "valid JSON"

JSLint, says Lots of errors due to "Missing space"

Here is the php script:

$cache = dirname(__FILE__) . '/cache/json.txt';

$data = file_get_contents('http://api.twitter.com/1/statuses/user_timeline/screen_name.json?count=1&include_rts=true&include_entities=true');   

    $cachefile = fopen($cache, 'wb');
        fwrite($cachefile, $data);
        fclose($cachefile);

I've tried adding different lines with json_decode and json_encode, but so far no luck.

Please tell me what needs to be added to this script so that the text file has the JSON format with the spaces and line breaks.

The generated txt file is being used in a jQuery script so it needs t开发者_如何转开发o have perfect JSON format.

Thank you in advance!


It has no line breaks or spaces because this is what you get as response. Just put the URL in the address bar and you will see it.

JSLint is for validating JavaScript code, it does not make sense to use it for JSON.

As long as the JSON is valid (which seems to be the case), you are fine. No need to change anything. Every JSON parser ignores white spaces and line breaks anyway.


I figured out the problem and found the fix at http://php.net/manual/en/function.fwrite.php

It turns out that the txt file generated by the PHP script was not in UTF-8 format. I've updated the php script and it seems to be working now. Here is the final version of the php script:

$cache = dirname(FILE) . '/cache/json.txt';

$data = file_get_contents('http://api.twitter.com/1/statuses/user_timeline/screen_name.json?count=1&include_rts=true&include_entities=true');

$cachefile = fopen($cache, 'wb');
    fwrite($cachefile,utf8_encode($data));
    fclose($cachefile);

Thank you to those of you who gave answers, really appreciate it.


As I recently found out, JSON != JavaScript. A JSON string in JavaScript is just that, a string. Given that, you really wouldn't want line breaks as they are not valid in javascript strings.

The errors probably relate to JSLint attempting to parse it as a JavaScript Object as I would guess there aren't quotes around the whole JSON string. As long as JSON Lint says it is valid, then it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜