In a PHP script, I want to grab some json data that is being generated dynamically by another PHP script.
For an example, let's use this simple example of a dynamic PHP-generated JSON file:
<?php
// note: unlike this simplified example, the data in my script is dynamically generated
$some_data = array(
'color' => 'blue',
'number' => 33,
'length' => 'long'
);
header('Content-Type: application/json');
echo json_encode($some_data);
...which would render this json file:
{ "color": "blue", "number": 33, "length": "long" }
Now how do I include this PHP file from another PHP file so I can get that data dynamically?
If I use $data = include 'json_data.php';
, it doesn't store the data in my $data var, it takes the mime type header being defined in that include and determing the page is that mime type instead of determining the data from the include is that mime type and separate.
file_get_contents()
and fopen()
are only returning the actual PHP code, not rendering it and returning the resulting json data.
I could use cURL...
<?php
$c = curl_init();
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_URL, 'https://www.example.com/json_data.php');
header('Content-Type: application/json');
echo curl_exec($c);
curl_close($c);
...but doesn't that seem overkill for accessing a local file? Plus, that will take some extra setup work in my local vagrant dev environment to make my local file HTTP-accessible for cURL to be able to access it.