我有所需的ID变量,(有1-6个可能的值):
$new_product['ID'] =$row[2];
我需要的是根据这个变量回显一个单独的"php-include",所以类似于:
<?php include 'includes/size/prod/echo $row[2].php'; ?>
它将显示,包括/size/prod/1.php,包括/size/prod/2.php等
我不明白如何在php中表达"echo"。
有几种方法:
//Concatenate array value in double quotes:
<?php include "includes/size/prod/{$row[2]}.php"; ?>
//Concatenate array value outside of quotes:
<?php include "includes/size/prod/".$row[2].".php"; ?>
//or, using single quotes:
<?php include 'includes/size/prod/'.$row[2].'.php'; ?>
//Concatenate variable (not array value) in double quotes:
<?php $page = $row[2]; include "includes/size/prod/$page.php"; ?>
参见:
- http://php.net/manual/en/language.operators.string.php
- PHP-在字符串中连接或直接插入变量
- PHP包含路径中的一个变量
使用此技术包含PHP文件是非常危险的
您必须通过至少控制包含的文件来防止这种情况的发生
现在回答您的问题:
<?php
// ? $row2 contains more than 1 php file to include ?
// they are seperated by comma ?
$phpToInclude = NULL;
define(TEMPLATE_INCLUDE, 'includes/size/prod/');
if (isset($row[2])) {
$phpToInclude = explode($row[2], ',');
}
if (!is_null($phpToInclude)) {
foreach($phpToInclude as $f) {
$include = sprintf(TEMPLATE_INCLUDE . '%s', $f);
if (is_file($include)) {
// add validator here !!
include ($include);
}
else {
// file not exist, log your error
}
}
}
?>
请使用以下工作代码
$row[2] = '';
$file_name = !empty($row[2])?$row[2]:'default';
$include_file = "includes/size/prod/".$file_name.".php";
include($include_file);
事物以双引号进行评估,但不以单引号进行评估:
$var = "rajveer gangwar";
echo '$var is musician'; // $s is musician.
echo "$var is musician."; //rajveer gangwar is musician.
因此最好使用双引号
示例:
// Get your dynamic file name in a single variable.
$file_name = !empty($row[0]) ? $row[0] : "default_file";
$include_file = "includes/size/prod/$file_name.php";
include($include_file);
您可以使用点来分隔字符串:例如:
$path = 'includes/size/prod/'.$row[2].'.php';
include '$path';
或者你可以把它放在一个变量中:
$path = $row[2];
include 'includes/size/prod/$path.php';
Php能够计算字符串中的变量。