开发者

Push JSON Encoded Data To Website in what format?

I need to push some JSON data to my website which I would like to read in PHP. What type of file should I make this? A PHP file with the JSON inside of a variable? I understand how to make a text file with JSON encoded data in it, but how do I get this into PHP? Should I use a PHP include with the JSON-encoded data开发者_Go百科 in it assigned to a variable? Or should I read the file from PHP and put the contents into a variable?


Save your json string as plain text, then you can use:

$file = yourfile
$data = file_get_contents($file);
$parsed = json_decode($data);

// compacted:
$parsed = json_decode(file_get_contents($file));

See file_get_contents() and json_decode().

The advantage of doing this (versus storing it in a PHP file then including it) is that now any program or language that understands JSON can read the file.


The question is too vague for a definite "do this" answer, but here are some options and what they might be most suitable for:

Turn the json data into a PHP data structure. If this is a one-time thing (meaning you won't be getting a new json file every day or week or hour), then reading a file (file_get_contents) and parsing JSON (json_decode) for every request is a pretty big waste of resources since that data isn't changing on a regular basis. Just turn JSON key/value objects into PHP associative arrays, JSON strings into PHP strings, etc.

Just serve the json file. If this is data that will just wind up going to the client to be used in javascript anyway, there's no need to do anything special with it on the server, just parse the json on the client.

Put it in a database. This may be a little heavy-handed, but if you really need it in PHP and not just the client, and it is going to be changing or growing on a regular basis, it may be worth it to have something that handles this use case appropriately.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜