2010-11-09 118 views
0

我有一個函數,它使用file_get_content來抓取一塊帶有一些變量的html。然後這個想法是用這個函數從db中獲取並返回它的一些東西來更新變量。但是,在輸出上,變量只讀取$ myNameVar而不是我的名字。讓我粘貼我的代碼。file_get_content和變量問題

function query($query,$item) 
    { 
     $this->item = file_get_contents("/pages/items/".$item.".php"); 
     $this->queryResult = mysql_query($query); 
     if(mysql_num_rows($this->queryResult)) 
     { 
      while($row = mysql_fetch_assoc($this->queryResult)) 
      { 
       extract($row); 
       // $myNameVar = My Name; 
       // in the finished code there will be a bunch (15 or more) vars 
       // that needs to be updated in the Item file so the vars 
       // must be updated automatically 
       return $this->item; 

      } 
     } 
    } 

而且item.php的內容:

<p>My name is <span style="color: #000;">$myNameVar</span></p> 

這裏的調用函數:

<?php echo $queryDb->query("SELECT * FROM sometable","item");?> 

,這裏是輸出:

My Name is $myNameVar 

當它應該是:

My Name is My Name 

我試圖替換變量在item.php文件%%和運行一個foreach更新像這樣(不同的功能)的變量:

function query($query,$item) 
    { 
     $this->item = file_get_contents("/pages/items/".$item.".php"); 
     $this->queryResult = mysql_query($query); 
     if(mysql_num_rows($this->queryResult)) 
     { 
      while($row = mysql_fetch_assoc($this->queryResult)) 
      { 
       foreach ($row as $key => $value) 
       { 
        $this->item = str_replace("%".$key."%",$value,$this->item); 
       } 
       return $this->item; 

      } 
     } 
    } 

這部分工作,不幸的是,這只是返回每一行的第一項。因此,如果在第一行中,$ myNameVar = Joe,第二行$ myNameVar = James這兩個段落都會列出Joe的名字:Joe Joe,而不是Joe James。

任何幫助,將不勝感激:)

+0

在做了一些測試之後,在第一行中刪除了由於錯誤而留下的返回。 – Jay 2010-11-09 00:44:18

回答

2

這是因爲file_get_contents()通行證在文件作爲一個字符串,而不是可執行的PHP代碼的內容。

改爲使用include()

+0

謝謝,工作就像一個魅力!在這種情況下從來沒有使用過include()。 – Jay 2010-11-09 04:21:07

0

如果你希望你的代碼確實做了什麼你可能不應該有在第一線的回報。

function query($query,$item) 
     { 
      $item = file_get_contents("/pages/items/".$item.".php"); 
$this->queryResult = mysql_query($query); 
    if(mysql_num_rows($this->queryResult)) 
    { 
     while($row = mysql_fetch_assoc($this->queryResult)) 
     { 
      foreach ($row as $key => $value) 
      { 
       $this->item = str_replace("%".$key."%",$value,$this->item); 
      } 

return $item; 
+0

固定。在那裏有錯誤 – Jay 2010-11-09 00:51:56

0
<p>My name is <span style="color: #000;">$myNameVar</span></p> 

需要是

<p>My name is <span style="color: #000;"><?php echo $myNameVar ?></span></p> 
+0

是的那也是 – kalpaitch 2010-11-09 00:49:02

+0

謝謝,試過了,它只是輸出<?php echo $ myNameVar;?>而不是 – Jay 2010-11-09 00:50:12