File_get_contents 与 PHP 检索 JSON 当文件在同一服务器上时代码输出而不是源代码

File_get_contents with PHP to retrieve JSON output of code as opposed to source code when file is on same server

我有一个扩展名为 .php 的服务器文件,它从数据库中检索数据并将其输出为 JSON。我试图从同一目录中的单独文件获取此输出,但是,当我使用 file_get_contents 时,它不是检索输出,而是检索源代码。当应用到外部URL时,file_get_contents显然无法获取服务器上文件的来源而只能获取输出(尽管是输出的源代码)。

文件输出内容为:

header("Content-Type: application/json");
echo json_encode(array('item'=>$dataobject));

我正在尝试通过以下方式获取输出:

$object = file_get_contents("myfile.php"); 

什么是 属性 检索文件输出的方法,而不是文件位于同一目录时的源代码?

direct 路由将使用 URL 而不是文件路径,以便通过 HTTP 获取数据并且 Web 服务器生成对URL 通过执行 PHP 程序。

更好的方法是将代码重构为函数,包含文件,然后调用函数。

mylib.php

function getJSON() {
    return json_encode(array('item'=>$dataobject));
}

myfile.php

include("mylib.php");
header("Content-Type: application/json");
echo getJSON();

other.php

include("mylib.php");
$object = getJSON();

我不明白,你为什么要那样做。这不是一个好方法。但无论如何,这可能会有所帮助。

文件 1 - test1.php

<?php
echo json_encode(['year'=>2020]);
?>

文件 2 - test2.php

<?php
echo file_get_contents("http://localhost/test1.php");
?>

使用您的 url 删除本地主机。