I need a few small bits of data from Craft in a PHP file. It’s a really small task, so I don’t want to delve into writing plugins or anything hardcore.

It seemed to me the simplest way to approach it would be to use the ElementAPI plugin and then read the resulting JSON in the PHP (this is being tested using MAMP):


// ID of entry I want
$id = 563;

// Grab data from ElementAPI
$url = "http://localhost:8888/myApi/" . $id . ".json";
$data = file_get_contents($url);
$json = json_decode($data);

// output data
echo "Entry title: " . $json -> title;


This works perfectly.

However, that hard-coded URL does not sit well with me.

I tried grabbing the directory using a few variations, eg:

$url =  __DIR__ . "/myApi/" . $id . ".json";

That gave me the correct path to the file, but the JSON isn’t generated — presumably because without the hard-coded address it’s not running the file through MAMP, so the PHP isn’t running.

I surely cannot manually update the URL every time I deploy a revision — that seems like a disaster in the making.

TIA for any solutions.

  • 1
    What "small bits of data" are you asking for? What are you using that data for? Depending on what you're doing, you can also hook into Craft via a shell script but it would help to clarify your use case. Jul 18, 2020 at 21:00
  • I need to grab 1–3 products, and the title, primary image, and a list of options for each, and I need to do it in a PHP file due to other aspects of the project. In twig it would be no problem, and the above is working, I’m just baffled as to how to make the $url in the script flexible enough that I don’t need to hardcode it.
    – Mitrol
    Jul 19, 2020 at 17:10

1 Answer 1


You need the url, not the file path. Can you store the url, or the http://localhost:8888 part of it in an environment variable? That gives you

$url = getenv('CRAFT_URL') . $id . ".json";

If it is not already in an environment variable, then in a .env file? web/index.php that comes with Craft is a good example of loading a .env file, and then using the environment variable.

  • Thanks for the answer
    – Mitrol
    Jul 22, 2020 at 22:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.