[英]PHP - How to share JSON data between files
所以我正在尝试制作一个简单的 API,我尝试了很多不同的东西。 我想在我的 JSON object 上显示一个随机数和 go 的令牌,然后将两者存储在数据库中。 我不希望在您访问网页时发生这种情况,我希望将数据发送到数据库并从单独的页面生成。
第一步是从不同的文件中获取数据。
这是我首先尝试的:
索引.php:
<?php
$odds = rand(1, 100);
?>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{
"odds": <?php echo $odds;?>
}
</pre>
这是我试图从中获取数据的文件:
<?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;
?>
错误:
Notice: Trying to get property 'odds' of non-object in D:\xxamp\htdocs\random\perp.php on line 16
我之后尝试了什么:
索引.php:
<?php
$values = array("odds"=>rand(1, 100));
echo json_encode($values);
?>
这是我试图从中获取数据的文件:
<?php
$json = file_get_contents("index.php");
echo $json;
// echo $json->odds;
?>
错误:
It doesn't show any data or errors, just a blank screen.
有没有人有解决这个问题的方法? 我正在尝试为朋友建立一个可证明公平的系统。
您在两个示例中都非常接近:
#1
$data = json_decode($response, true);
echo $data->odds;
您将true
传递给json_decode
,这使其成为关联数组,而不是 object。 所以你需要用$data['odds'];
反而。
#2
$json = file_get_contents("index.php");
echo $json;
file_get_contents
可以获取本地文件或远程文件。 在本例中,您传递的是本地文件,因此$json
是 PHP 代码的内容。
您可以:
(a) 重新设计它,使index.php
是 function,您可以从不同的文件中调用 function
(b) 远程调用index.php
并解析结果
一个。 在index.php
中创建一个 function 可以得到赔率:
<?php
function getData() [
return array("odds"=>rand(1, 100));
}
然后,在另一个文件中,您可以:
<?php
require_once 'index.php';
$data = getData(); //now you have access to $data['odds'];
湾。 远程调用index.php
,像这样:
$json = file_get_contents("http://localhost/index.php");
print_r(json_decode($json, true));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.