2012-01-13 15 views
1

我們認爲mytext.txt包含:(PHP)充分利用使用變量的文件內容

你好,我的名字是$名稱。

則...

<?php 
$name = "Johnny"; 
$output = file_get_contents("mytext.txt"); 
echo $output; 
?> 

我這樣做是希望$命名與變量的值來代替。

ps:我不能使用include(),因爲我需要將它存儲在一個變量中。

+0

非常好的問題。那種問題已經讓我想起了另一個項目。你有我的投票,我認爲答案顯然是足夠的。可能你應該接受其中的一個。 – motto 2012-01-13 05:26:15

回答

3

呦必須使用輸出緩衝,就像這樣:

<?php 
$name = "Johnny"; 
ob_start(); 
include "mytext.txt"; 
$output = ob_get_contents(); 
ob_end_clean(); 
echo $output; 
?> 

而且你的文件的格式必須爲PHP:

Hello, my name is <?php echo $name ?> 

這樣一來,你有你的文件。你的文件被稱爲php,你可以將輸出的html作爲變量存儲。 這裏更多的信息:http://php.net/manual/en/book.outcontrol.php

+0

剛剛嘗試過。它顯示了同樣的事情:你好,我的名字是$ name。 – user1091856 2012-01-13 04:48:20

+0

編輯我的文章,重新格式化您的txt文件 – Kristian 2012-01-13 04:49:39

+0

如果您需要保留文件格式比您必須編寫一些模板引擎,什麼'preg_replace()'或'str_replace()'將remplate變量。或者使用一些模板引擎:http://www.webresourcesdepot.com/19-promising-php-template-engines/ – Kristian 2012-01-13 04:52:11

0

mytext.txt

<?php 
$str = "Hello my name is $name."; 

your.php

<?php 
$name = "Johnny"; 
require_once 'mytext.txt'; 
echo $str; 
1

使用pregmatch都將成爲神的方式,這裏是工作的例子,我已經嘗試過,只需刪除$並更改爲[name]從您的變種

<?php 
$name = "Johnny"; 
$output = file_get_contents("data.txt"); 
echo preg_replace('/\[name\]/',$name,$output); 
?> 

和mytext.txt只是把這樣的Hello my name is [name].

,其結果將是Hello my name is Jhonny.

+0

它會輸出'Hemmo我的Jonnhy是Jonhhy' :) – Kristian 2012-01-13 04:57:31

+0

ahh sory,我的錯誤,看看代碼,編輯:) – 2012-01-13 05:01:33

+0

這不是一個壞主意。但我的文章只是舉了一個例子。在我的網絡應用程序中實際上有一個包含大量變量的文本文件,因此我需要爲每個變量預置一個preg_replace,這似乎不是一個非常好的方法。 – user1091856 2012-01-13 05:02:17