gpt4 book ai didi

PHP file_get_contents(file.php);执行文件中的PHP代码

转载 作者:行者123 更新时间:2023-12-03 09:03:22 24 4
gpt4 key购买 nike

我目前遇到一个问题,我在一个文件中有一些 php 代码并从另一个文件调用该文件。

所以:

index.php正在调用file.php并且file.php中有一些php代码。

我使用file_get_contents的原因是我在index.php中有代码,只需要读取file.php中由标签指定的一些内容。基于 ($_GET['identifier']) 触发的节标记; file.php 中的该部分是唯一显示的部分

file.php 中的示例代码:

<?php
//simplified php code
var $item = "hello";
var $item2 = "Hola";
var $item3 = "おはよ";
?>

<section id="content">
<?php echo $item1; ?>
</section>
<section id="content2">
<?php echo $item2; ?>
</section>
<section id="content3">
<?php echo $item3; ?>
</section>
?>

index.php 中的代码:

$content = file_get_contents('file.php');
if (isset($_GET['item'])) {
$section = $_GET['item'];
} else {
$section = 'content';
}
$delimiter = '<section id="' . $section . '">';
$start = explode($delimiter, $content);
$end = explode("</section>", $start[ 1 ] );
echo $end[0];

因此,如果浏览器 URL 显示 index.php?item=content2 ,它应该显示名为 content2 的节 ID 中的内容,以及该文件中执行的 PHP 代码。

目前,如果我这样做,不会显示任何内容,并且查看源代码,显示 php 代码

最佳答案

要在获取内容之前执行代码,您需要包含并捕获输出:

ob_start();
include('file.php');
$content = ob_get_clean();

或者通过 URL 获取文件(可能不是最好的主意并且不可移植):

$content = file_get_contents('http://example.com/file.php');

关于PHP file_get_contents(file.php);执行文件中的PHP代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com