Why does file_get_content fails to locate file when the directory is correct?
I have a test shortcode to read a JSON file:
function test( ) {
$strJsonFileContents = file_get_contents("./node.json");
$array = json_decode($strJsonFileContents, true);
echo var_dump($array); // print array
}
add_shortcode( 'test', 'test' );
Adding this shortcode into a post I can't update it due to the error
Updating failed. The response is not a valid JSON response.
Following the article How to Fix The Invalid JSON Error in WordPress (Beginner's Guide), I activate the Health Check & Troubleshooting, use the Classic Editor add the debug code into the wp-config.php :
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
And this is the result:
Warning: file_get_contents(./node.json): failed to open stream: No such file or directory in /home/xnqucuhr5aza/public_html/wp-content/plugins/Custom 1/Custom plugin.php on line 67
NULL
Why does this happen? The file is in the same directory to the plugin (i.e. /home/xnqucuhr5aza/public_html/wp-content/plugins/Custom 1/node.json). I then try file_get_contents(__DIR__ . '/node.json');
but it just says NULL
and nothing else.
The "not a valid JSON response" error is because your shortcode is written incorrectly.
As documented, shortcodes need to return their output. Otherwise it will be printed as soon as WordPress processes the shortcodes, which is before they are output.
In this case it causes the output of your shortcode to be printed at the beginning of an API response in the editor, breaking the formatting of that response.
You need to return the output of the shortcode:
function test( ) {
ob_start();
$strJsonFileContents = file_get_contents("./node.json");
$array = json_decode($strJsonFileContents, true);
var_dump($array); // print array
return ob_get_clean();
}
add_shortcode( 'test', 'test' );
Because you're using var_dump()
, which only prints, I have used output buffering to capture the output and return it.