如何获取PHP变量的JSON响应?

时间:2016-04-16 07:39:15

标签: php json getjson

我从像

这样的php文件发送json响应
$start = 2;
$startJson = array('start' => $start);
echo json_encode($startJson);

在另一个php文件中收到JSON响应,例如{“start”:“2”} enter image description here

现在如何将此数据“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响应吗?

1 个答案:

答案 0 :(得分:1)

file_get_contents()将整个文件读入字符串,因此不会执行您的php脚本。你必须在你的sortCategory.php文件中只放入json值(不需要放置.php扩展名,也可以使用.txt)。如果你想运行php脚本,那么你可以使用includerequire函数。

您可以使用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会更好。