我从像
这样的php文件发送json响应$start = 2;
$startJson = array('start' => $start);
echo json_encode($startJson);
在另一个php文件中收到JSON响应,例如{“start”:“2”}
现在如何将此数据“2”提取到PHP变量。我试过..
$json = file_get_contents('sortCategory.php');
$data = json_decode($json);
echo data;
之后我收到了这个错误:
Notice: Use of undefined constant data - assumed 'data' in F:path to .php on line 322
请提供任何解决方案来获取对PHP变量的JSON响应吗?
答案 0 :(得分:1)
file_get_contents()
将整个文件读入字符串,因此不会执行您的php脚本。你必须在你的sortCategory.php文件中只放入json值(不需要放置.php扩展名,也可以使用.txt)。如果你想运行php脚本,那么你可以使用include
或require
函数。
您可以使用file_get_contents()
:
<强> sortCategory.php 强>
{"start":2} // array in json format
<强>的index.php 强>
<?php
$json = file_get_contents('sortCategory.php');
$data = json_decode($json);
print_r($data);
?>
在这种情况下,您无需将文件命名为.php
扩展名。 sortCategory.json
会更好。