Setting relative path to ElementAPI in PHP 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):
&lt;?php

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

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

// output data
echo &quot;Entry title: &quot; . $json -&gt; title;

?&gt;

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__ . &quot;/myApi/&quot; . $id . &quot;.json&quot;;

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.
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 . &quot;.json&quot;;

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.