[英]PHP Include file but only first few lines
我正在使用PHP包括:
< ?php include 'file1.php'; ?>
?php include 'file1.php'; ?>
我想只包含file1.php的前几行 - 这可能吗?
如果你真的想要include
(运行为PHP),那么只需将这些行拉出到一个新文件中:
new.php :
<?php
// line 1
// line 2
并将其包含在两个文件中:
existing.php和other.php :
<?php
include('new.php');
...
<?php
$return_from_inc = include('file1.php');
?>
file1.php
<?php
if ($x === 1) { return 'A'; }
else { return 'B'; }
//... return ("break") running script wherever you want to
?>
根据第一行的内容,为什么不使用PHP函数?
file1.php
<?php
function what_i_want_to_include(){
//"First lines" content
}
}
existing.php
<?php
include('file1.php');
what_i_want_to_include();
?>
使用函数它是最简单的方法。
您可以简单地在您选择的行上使用return
,并将控制权发送回调用文件。
如果在函数内调用,则return语句立即结束当前函数的执行,并将其参数作为函数调用的值返回。 return也将结束eval()语句或脚本文件的执行。
如果从全局范围调用,则结束当前脚本文件的执行。 如果包含或需要当前脚本文件,则将控制权传递回调用文件。 此外,如果包含当前脚本文件,则返回的值将作为include调用的值返回 。 如果从主脚本文件中调用return,则脚本执行结束。 如果当前脚本文件由php.ini中的auto_prepend_file或auto_append_file配置选项命名,则该脚本文件的执行结束。
来源: PHP手册
有几个选项可以实现这一点,但让我强调,如果这对您的应用程序工作是必要的,您应该考虑审查应用程序设计。
如果你以编程方式想要它,你可以抓住前面的x行并使用eval()来解析它们。 例:
$file_location = '/path/to/file.php';
$number_of_lines = 5; //
$file_array = file($file_location);
if(!$file) {
return false; // file could not be read for some reason
}
$first_lines = array_slice($file_array, 0, $number_of_lines);
$to_be_evaluated = implode('', $first_lines);
eval($to_be_evaluated);
但你不应该认为eval期望一个没有php开始标记的字符串( <?php
),至少在开始时不是这样。 所以你应该搜索它并在第一行(如果存在)中删除它:
if(strpos($first_lines[0], '<?php') !== false) {
$first_lines[0] = substr(strpos($first_lines[0], '<?php') + 5);
}
另一个更好的选择,如上所述,只需拉出所需的行,将它们保存到另一个文件,并将它们包含在两者中。 您也可以以编程方式执行此操作,甚至可以提取所需的行并将其保存到临时文件中。
编辑它是一个“奇怪”的问题,从某种意义上说它不应该是必要的。 你能解释一下你究竟想做什么吗? 最有可能我们可以提出一个不错的选择。
编辑
据我所知,你在文件中有很多东西,但只需要数据库设置。 在那种情况下,把它们放在别处! 例:
的settings.php
$connection = new mysqli($host, $user, $pass, $db);
if($connection->connect_error) {
die('This failed...');
}
header.php文件
<?php require_once('settings.php'); ?>
<html>
<head>
<title>My awesome website</title>
... other stuff
</head>
other_file.php
<?php
require_once('settings.php');
$r = $connection->query('SELECT * FROM `my_table` WHERE `random_field`=`random_value`');
等等
在settings.php中,您还可以将所有内容放在函数中,以确保只在需要时执行。 您可以在示例中创建一个get_connection()
函数,该函数检查数据库连接是否存在,否则创建它并返回它以供使用。
根本不需要花哨的eval()
函数!
请记住,将您的申请分成一千个文件并不构成犯罪。 真的不是!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.