简体   繁体   中英

PHP - How to share JSON data between files

So I'm trying to make a simple API, I have tried lots of different things. I want to show a random number on my JSON object and a token to go with it, then store both in a database. I don't want this to happen when you visit the webpage I want the data to get sent to a DB and generated from a separate page.

The first step in this is getting data from a different file.

Here's what I tried first:

index.php:

    <?php

$odds = rand(1, 100);

?>

<pre style="word-wrap: break-word; white-space: pre-wrap;">
{
    "odds": <?php echo $odds;?> 
}
</pre>

Here's the file I'm trying to get the data from:

    <?php

$url = "https://flugscoding.com/random/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Riverside API");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

if(!$response = curl_exec($ch)) {
echo curl_error($ch);
}
curl_close($ch);

$data = json_decode($response, true);
echo $data->odds;
?>

Error:

Notice: Trying to get property 'odds' of non-object in D:\xxamp\htdocs\random\perp.php on line 16

What I tried after:

index.php:

     <?php

$values = array("odds"=>rand(1, 100));
echo json_encode($values);

?>

Here's the file I'm trying to get the data from:

<?php

$json = file_get_contents("index.php");        
echo $json;     
// echo $json->odds;

?>

Error:

It doesn't show any data or errors, just a blank screen.

Does anyone have any solutions to this problem? I'm trying to make a provably fair system for a friend.

You're really close in both your examples:

#1

$data = json_decode($response, true);
echo $data->odds;

You're passing true into json_decode which makes it an associative array, not an object. So you will need to get the odds with $data['odds']; instead.

#2

$json = file_get_contents("index.php");        
echo $json;   

file_get_contents can either fetch a local file or remote file. In this case, you're passing a local file, so $json is the contents of the PHP code.

You can either:

(a) redesign it so that index.php is a function, and you can call the function from different files
(b) call index.php remotely and parse the results

a. Create a function in index.php that can get the odds:

<?php

    function getData() [
        return array("odds"=>rand(1, 100));
    }

Then, in another file, you can:

<?php

    require_once 'index.php';

    $data = getData(); //now you have access to $data['odds'];

b. Call index.php remotely, like this:

$json = file_get_contents("http://localhost/index.php");        
print_r(json_decode($json, true));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM