TransWikia.com

Setting relative path to ElementAPI in PHP

Craft CMS Asked by Mitrol on September 4, 2021

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):

<?php

// 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.

One Answer

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.

Correct answer by Marion Newlevant on September 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP