S
S
Sergey Bulgakov2021-09-19 22:26:17
PHP
Sergey Bulgakov, 2021-09-19 22:26:17

Why doesn't the file_get_contents('folder/file.json') call work?

Hello,
I have a landing page with the following structure:

index.php
 |
 +-assets
 |    +-html - тут все части лэндинга - файлы php и html (header, footer, form ...)
 |    |  |
 |    |  +-data - тут json файлы для загрузки данных
 |    |  |  |
 |    |  |  +-persons.json - сотрудники
 |    |  |  |
 |    |  |  +-news.json - новости


The index.php file simply contains the call to the required modules from 'assets/html/'. Those. So
<?php 
  require_once '/assets/html/file.php';
?>


The 'data' directory (full path 'assets/html/data') contains json files that contain all the information that needs to be displayed.

In any file (for example top_news.php) in the html directory ('assets/html') I write:
<?php
  $url = 'data/news.json'; //путь до json файла json
  $data = file_get_contents($url);
?>


The problem is that file_get_contents($url) doesn't see the right file.

I get the response (on screen)

'Warning: file_get_contents(data/news.json): failed to open stream: No such file or directory in C:\OpenServer\domains\tnv4\html\top_news.php on line 3'

I tried place the data directory (with nested json files) in the assets folder (that is, assets/data/news.json).

But calling the news.json file with
$url = '../data/news.json';
$data = file_get_contents($url)
;

doesn't work either.

Locally I am using openserver, php_7.1

On server: centos 7.9, PHP 5.4.16

Please guide me how to get the json file correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nokimaro, 2021-09-19
@nokimaro

$url = __DIR__.'/data/news.json';
$data = file_get_contents($url);

__DIR__ will contain a directory relative to the file in which the execution takes place
For the file, the C:\OpenServer\domains\tnv4\html\top_news.phpcorresponding value will be
C:\OpenServer\domains\tnv4\html
Try to always use full paths, not relative ones

S
Sergey Bulgakov, 2021-09-20
@ivanovskii49

Itself guessed to use an absolute path (below).
But anyway, thanks a lot for your comments!
True, now, another even more strange error has appeared:

$path_to_jsonFolder = '/var/www/.../data/www/site.ru/assets/data/';
$a = $path_to_jsonFolder . 'all-news.json';

$string = file_get_contents($a); //работает

$a = json_decode($string, TRUE);//не работает, возвращает Null. 
echo $a; //Null

I absolutely cannot understand how.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question