Push JSON Encoded Data To Website in what format? - php

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 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.

Related

Write object in JSON file [duplicate]

This question already has answers here:
How to add to JSON array in .json file
(2 answers)
Closed last year.
I have a project based on PHP with OOP structure. When I register a user, it creates a user object and writes that object to json file. The problem is, in this way each time I create a user, the json object stores separately in the file.(shown in the image)
So when I re-read this json file using json_decode() function, it doesn't read anything. I've used the following method to check the file reading.
$data = json_decode(file_get_contents($file), true);
$f = fopen("log", 'a');
fwrite($f, $data);
So how can I append the json objects as list of arrays(upon registering a single user) or read all the entries from the file?
Most of the solutions that I have seen are predefined arrays, but in my case the objects are being created at runtime and only one at a time.
I agree with #Konstantinos Gounaris. The json file is in wrong format. That's why the json_decode function returned nothing. Always use json_encode while writing the json file and write it in one flow. If you want to append to the file, just read the contents, decode it and write it again. Don't append to the file, because it will break the json format.
#Note: Saving confidential information to the file is wrong practice, which leads to security issues.
It is a better practice to use databases to store data(they are more secure than files). However. The first thing that i can see that is wrong is that you are decoding the json file into an php array and then you are writing this array into a file, this results into wrong Json format.
Bellow is an example of how you should do it:
$data_to_import = ['name'=>'John','surname'=>'Doe'];
$data_array = json_decode(file_get_contents($file), true);
array_push($data_array, $data_to_import);
$f = fopen("log", 'a');
fwrite($f, json_encode($data_array));

JSON with Variable At Beginning?

I am loading an external JSON file. Which seems to load fine. Im using this script to load it:
$file ="https://creator.zoho.com/api/json/los/view/All_clients?
authtoken=xxx";
$bors = file_get_contents($file);
When i dump the results, I get:
string(505) "var zohoappview55 = {"Borrowers":[{"Full_Name":"Mike Smith","Email":"dadf#gmail.com","Address":"111 S. Street Ct., Aurora, CO, 80012","Position":"Borrower","ID":"1159827000004784102","Mobile":"+13033324675","Application":"Application 1 - 1159827000004784096"},{"Full_Name":"Stacy Smith","Email":"sdfa#gmail.com","Address":"111 S. Street, 80012","Position":"Co-Borrower","ID":"1159827000004784108","Mobile":"+1303558977","Application":"Application 1 - 1159827000004784096"}]};"
Looks like the json has a predefined var zohoappview55 at the begining of the json. Not sure if this is my issue but when i use json_decode it doesn't not decode. If i remove this beginning variable it decodes just fine.
i don't have a way to change this variable or edit the json file as it's a remote file. Does anyone know how to decode it in the native format with the variable at the beginning?
Having a quick look through the API documentation of zoho, it seems it should normally return correct json. It may think that it's a browser requesting the file as a javascript source so you may need to add an Accept header to your request.
This cannot be done with file_get_contents so you will probably need to use curl instead.
Try to perform a normal php curl request with the header Accept: application/json.
See: PHP cURL custom headers for reference.
But as Alex Howansky said in the comment. The API might not be intended for that. In that case you will need to strip the beginning and end of the received document.

PHP: Merge multiple JSON encoded lines

When users keep interacting with my web app, the pages keep doing calls so that some info can be stored in a cookie linked file that is stored on the server (with the PHP session file, it gets complex: I don't have choice to see a complete history, etc.)
So, anyway, with every ajax call, I create json_encoded data in a flat file with the unique cookie name.
Data example of one such cookie file: (keys/values may repeat)
{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}
Now, when I am searching this file, to retrieve data and to do other stuff, I would like to have the entire contents in one big array as if the entire data ws json_encoded in one shot.
How do I do this? I could do a bunch of str_replace and replace the "{" and "}" and get rid of the carriage returns but that seems to be a bit ugly
Is there a better way?
Thanks
I suggest to fix your json format by using str_replace as you saying because this is the only way to have a valid json format on using this function:
$str = '{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}';
$fix_json = "[" . str_replace("}\n{", "},{", $str) . "]";
and after this you can decode you json and convert it with json_decode, like this:
$dataArray = json_decode($fix_json, true);

Show php print_r in Flash?

Trying to figure out a way to get ActionScript to print out a php object. In PHP, I can just do print_r, and I'm able to successfully get the object into Flash, but now can't figure out how to print out the object using ActionScript 3?
Well, when the request first comes over, there is always URLLoader.data, which is data in its raw form. If you're looking to get the data from a JSON-style object, there is for( var i:String in obj ). If you're looking for things more obscure than that, there is the ability to use describeType. My favorite example of the last one is in the JSONEncoder class.
From PHP, you can encode most objects to JSON using json_encode() (PHP5+). Using the AS3 JSON decoder from as3corelib you can then convert that encoded string into an oject that AS3 con read. After that you can iterate over the object as key/value pairs and output it however you wish.
I think I know what you mean, I had the same need, so I made this
http://www.actionscript.org/forums/showthread.php3?t=266979
scroll to the bottom, there is a description and an .AS file called trace_r that I wrote

php how to write data into json?

I am newer for php. I want make php page cache, query data from mysql and store data into json format.
I have many questions:
which type of file should I store? .json or .txt or .cache? for I also need use json decode return datas into page.
I want use cron tab, make many mysql queries and write into one json file. what write code should I choose? fopen, fwrite or file_get_contents or other command? (do not cover the data, but continue write. I will deleted the file and renewer it at the next cron time)
If a multi write into a json data (10 or more mysql query at the same time and write into a same json file, each json child format like {name: ".$row['name']."}), how to completed a top { and bottom } to make a standad json data format?
{ //how to add this one
{name: ".$row['name']."}
{name: ".$row['name']."}
// many name from 10 more mysql queries
} //and this one
Thanks.
It's json_encode()
json_encode() — Returns the JSON representation of a value
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
which type of file should I store
It doesn't matter. There is no fixed extension, but I would pick .json just to make it clear what the file is supposed to contain.
what write code should I choose?
Just use file_put_contents to put the JSON string (see next section) into a file.
each json child format like
You really do not want to use that method. It might work for a while, but becomes very complex when you need to handle things like quoting and special-character escapes. Instead of re-inventing the wheel, use PHP's built-in JSON functions for this.
Create the data-structure you want using PHP's strings, numbers, and arrays, and then rely on json_encode to turn it into a string.
The main thing to be careful of is that depending on how your php array() looks, you might get JSON [] versus {}.
As far as saving the file as .txt or .json won't make a difference.
I think the focal point of this all lies in the json_encode page. Here's the example from that page:
This code:
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Outputs like this:
{"a":1,"b":2,"c":3,"d":4,"e":5}
3 . You can use fopen and fwrite to write to your file. The second argument to fopen is the mode, you want to use 'a' for append.
Don't write your own cache because anything you write in PHP will be slower than can be supported by native extensions (like APC or memcached or even MySQL itself!!).
Don't cache as JSON. JSON is not a particulary 'fast' to serialize. If you're doing caching you don't want to do any serialization at all. Just store it as it is.
MySQL does query caching for you. If performance is a problem first tune your MySQL queries and database schema. Caching is one of the absolute last optimization you want to do.
If you want an easy way to cache, make a MySQL table called 'cache' and use that. If you want quick (small) file access, use MySQL (seriously). If you want an even faster cache access use an in-memory cache like APC or memcached.

Categories