如何读取包含php代码的csv文件


How to read a csv file with php code inside?

我在谷歌上搜索了一下,但没有找到适合我问题的东西,或者我搜索错了单词。

在我阅读的许多线程中,smarty模板是解决方案,但我不会使用smarty,因为它对这个小项目来说太大了。

我的问题:

我得到了一个CSV文件,这个文件只包含HTML和PHP代码,它是一个简单的HTML模板文档,例如我用来生成动态图像链接的phpcode。

我想在这个文件中阅读(这很有效),但我如何处理这个文件中的php代码,因为php代码显示为原样。我在CSV文件中使用的所有变量仍然有效。

短版

如何在CSV文件中处理、打印或回显php代码。

非常感谢,

很抱歉我的英语不好

格式化上面的注释,您会得到以下代码:

$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
   $zeile = fgets($userdatei);
   echo $zeile;
}
fclose($userdatei);
// so i read in the csv file and the content of csv file one line:
// src="<?php echo $bild1; ?>" ></a>

这是假设$bild1是在其他地方定义的,但请尝试在while循环中使用这些函数来解析和输出html/php:

$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
   $zeile = fgets($userdatei);
   outputResults($zeile);
}
fclose($userdatei);
//-- $delims contains the delimiters for your $string. For example, you could use <?php and ?> instead of &lt;?php and ?&gt;
function parseString($string, $delims) {
    $result = array();
    //-- init delimiter vars
    if (empty($delims)) {
        $delims = array('&lt;?php', '?&gt;');
    }
    $start = $delims[0];
    $end = $delims[1];
    //-- where our delimiters start/end
    $php_start = strpos($string, $start);
    $php_end = strpos($string, $end) + strlen($end);
    //-- where our php CODE starts/ends
    $php_code_start = $php_start + strlen($start);
    $php_code_end = strpos($string, $end);
    //-- the non-php content before/after the php delimiters
    $pre = substr($string, 0, $php_start);
    $post = substr($string, $php_end);
    $code_end = $php_code_end - $php_code_start;
    $code = substr($string, $php_code_start, $code_end);
    $result['pre'] = $pre;
    $result['post'] = $post;
    $result['code'] = $code;
    return $result;
}
function outputResults($string) {
    $result = parseString($string);
    print $result['pre'];
    eval($result['code']);
    print $result['post'];
}

CSV文件中包含应该使用eval解析并可能执行的PHP代码对我来说非常危险

如果我说得对,你只想在你的CSV文件中有动态参数,对吗?如果是这种情况,并且您不想在应用程序中实现整个模板语言(如Mustache、Twig或Smarty),则可以执行简单的搜索和替换操作。

$string = "<img alt='{{myImageAlt}}' src='{{myImage}}' />";
$parameters = [
    'myImageAlt' => 'company logo',
    'myImage' => 'assets/images/logo.png'
];
foreach( $parameters as $key => $value )
{
    $string = str_replace( '{{'.$key.'}}', $value, $string );
}