PHP include语句包含echoed PHP变量

时间:2015-12-01 10:36:35

标签: php

我有这个必需的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内。

5 个答案:

答案 0 :(得分:0)

有几种方法:

//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"; ?>

请参阅:

答案 1 :(得分:0)

您可以使用点来分隔字符串: 例如:

$path = 'includes/size/prod/'.$row[2].'.php'; 

include '$path';

或者你可以把它放在一个变量中:

$path = $row[2];
include 'includes/size/prod/$path.php'; 

Php能够评估字符串中的变量。

答案 2 :(得分:0)

使用此技术包含 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
        }
    }
}

?>

答案 3 :(得分:0)

亲爱的使用以下工作代码

$row[2]         =   '';
$file_name      =   !empty($row[2])?$row[2]:'default';
$include_file   =  "includes/size/prod/".$file_name.".php";
include($include_file);

答案 4 :(得分:0)

事情用双引号评估,但不是单引号:

$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);