简体   繁体   English

file_get_contents()无法读取PHP标记<?php ?>

[英]file_get_contents() cannot read PHP tags <?php ?>

I am using cakePHP and got stuck with this riddle. 我正在使用cakePHP,并陷入了这个谜语。 Time ago i made function that inserts custom routes dynamically in file using file_get_contents() and string replace functions. 前段时间,我做了一个函数,该函数使用file_get_contents()和字符串替换函数在文件中动态插入自定义路由。

$filename = "301routes.php";
$path = SERVER_PUBLIC_PATH . 'app' . DS . 'config';
$add_data = "Router::connect('".$old."', array('controller'=>'index_router', 'action'=>'redirect_301','".$new."'));\n";
$file_data = file_get_contents($path . DS . $filename);
$file_data = str_replace("<?php\n","<?php\n".$add_data,$file_data);
file_put_contents($path . DS . $filename, $file_data);

this worked, but now i tried to put exactly the same function in other project and its working only when there is no PHP tag. 这行得通,但是现在我试图将完全相同的功能放在其他项目中,并且仅当没有PHP标记时才起作用。 Problem is with file_get_contents() function becouse it reads file well when content is: 问题在于file_get_contents()函数,因为当内容为:

// routes here
Router::connect('/articles/category/en/test', array('controller'=>'index_router', 'action'=>'redirect_301','/articles/category/en/test-old'));

but when i change beginning like this 但是当我这样改变开始时

<?php
Router::connect('/articles/category/en/test', array('controller'=>'index_router', 'action'=>'redirect_301','/articles/category/en/test-old'));
?>

file_get_contents() returns only part of file: file_get_contents()仅返回文件的一部分:

string(154) "'index_router', 'action'=>'redirect_301','/articles/category/en/test-old')); ?>"

Can someone help me with this? 有人可以帮我弄这个吗?

To run php codes and assign to $file_data variable, 要运行php代码并分配给$ file_data变量,

ob_start();
$file_data = file_get_contents($path . DS . $filename);
ob_end_flush();
Try: Create new file 301routes.php in config directory then read write permission of file.
$filename = "301routes.php";
$path =  __DIR__;
$add_data = "Router::connect('".$old."', array('controller'=>'index_router', 'action'=>'redirect_301','".$new."'));\n";
$file_data = file_get_contents($path . DS . $filename);
$file_data = str_replace("<?php\n","<?php\n".$add_data,$file_data);
file_put_contents($path . DS . $filename, $file_data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM