Dave31415
Dave31415

Reputation: 2956

How best to pass a python dictionary to PHP using file IO

I have a python script running on a cron job, once a minute, which builds some data into a dictionary. I am writing that data into a simple, space separated, text file and reading that into PHP whenever the webpage is requested.

What is correct way to do pass this information? What I am doing now certainly feels clunky since I am rebuilding essentially the same structure in PHP. How do I just write my python dictionary (perhaps an order dictionary is needed) to disk so that PHP can read it directly into a PHP array?

I also worry a bit about whether this method of transfer is kinda archaic. Should I be using a database instead, e.g. SQLlite? I worry that someone will load the page as the file is being updated which might cause some problems.

I just need something light and simple. Don't want to overcomplicate it. Thanks in advance.

Upvotes: 1

Views: 2105

Answers (2)

bigblind
bigblind

Reputation: 12867

Any language can read JSON, as JSON is simply a way to format data as text, which can easily be parsed by any program. To write the dictionary as a json file, you do this:

import json
myfile = open('data.json','w+')

#create your dict

json.dump(mydict,myfile)
myfile.close()

now to read it in PHP:

$data = json_decode(file_get_contents("data.json"));

Upvotes: 3

senderle
senderle

Reputation: 151007

I don't know whether PHP handles json data, but if so, that's probably the way to go. See the json module documentation for more...

And in fact, PHP does handle json data: http://php.net/manual/en/book.json.php

This should be a relatively simple but robust way to transfer the data.

Upvotes: 1

Related Questions