kursus kursus - 10 months ago 25
PHP Question

Best practise to repeatedly use a local JSON file in a no-framework PHP code

It's a simple PHP script with no framework of any kind. I get a very large (15MB, I have no choice but deal with it) local json file and use it for different operations.

Right now I use the

keyword to call it from functions but it doesn't feel very good. I also wonder about performances. Is there a more proper simple way to do for this kind of purpose ?

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

function randomItem() {
global $data;
return array_rand($data);

$item = randomItem();


You can write it like :

class JsonLoader{
    private $data;
    private $arrayEncoding;
    public function load($file,$arrayEncoding = true){
        if(file_exists($file) == false){
            return false;
        $this->arrayEncoding = $arrayEncoding;
        $this->data = json_decode(file_get_contents($file),$arrayEncoding);
        if($this->data == null){
            return false;
        return true;
    public function getData(){
        return $this->data;
    public function getRandomData(){
        return (is_array( $this->data ) ? array_rand($this->data) : array_rand((array)$this->data));

And use it like :

$json = new JsonLoader;

if( $json->load("data.json") == false ){
    //Show Error

$random = $json->getRandomData();