Click here to Skip to main content
15,664,619 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
this is my (json.php) file which i try to get through file_get_contents('url/file/json.php') and try to decode it.

$query = "select * from tbl-item";
$stmt = $conn->query($query);
$json_array= array();
while($row= $stmt->fetch(PDO::FETCH_ASSOC)){
echo json_encode($json_array);
file_put_contents('my_file_json.json', json_encode($json_array));

What I have tried:

$json = file_get_contents('url/file/json.php');
$data = json_decode($json, true);
foreach ($data as $key => $value)
Updated 20-Oct-21 5:37am
Peter_in_2780 19-Oct-21 22:17pm    
As a first guess, I'd say that your JSON is badly formed, and can't be decoded into $data.
In this case, your foreach will fail as $data will be null.
A Ali_786 20-Oct-21 0:33am    
So what should I need to do for decoding json data.
any suggestion.
Peter_in_2780 20-Oct-21 1:05am    
First, check that $data is indeed null at that point, then examine $json to figure out why.
You need to debug this yourself. We can't see what your data is.
A Ali_786 20-Oct-21 1:19am    
I checked this url in browser $json = file_get_contents('url/file/json.php');
data are present in the form of json but when i try to decode. it show warrning.
Peter_in_2780 20-Oct-21 1:36am    
You need to look at the warning message and fix what it is warning you about.
We can't do that for you.

1 solution

The file_get_contents[^] method reads the contents of the specified file. It does not execute the code stored in that file.

Your file contents are PHP script, not JSON.

If you want to execute the PHP script and load the result, you will need to specify the complete URL to the script. You cannot use a relative URL, since that will be interpreted as a file path.
$json = file_get_contents('https://www.yoursite.local/url/file/json.php');

If that still doesn't work, then you need to debug your code to examine the contents of the $json variable.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900