2015-12-10 27 views
3

我有這樣的代碼放到一個函數(PHP類):的file_get_contents管腔

$theFile = '/test/test.xml'; // these are in the public folder 
dd(file_get_contents($theFile)); 

如果我去mydomain.local/test/test.xml,給我的工作XML代碼。

但隨着file_get_contents,我得到這個錯誤:

file_get_contents(/test/test.xml): failed to open stream: No such file or directory 

如何解決這個問題?

+0

'的file_get_contents()'相對執行你的PHP腳本(你不會擺弄米如果你有這條路,真正的代碼正確執行,導致laravel如何工作)。使用'base_path()。 「/測試/ test.xml''。 –

+0

@Tezla這個你爲什麼不讀[文檔]不起作用 – Zl3n

+0

宕,(http://laravel.com/docs/5.1/helpers#method-public-path),它是在你所能的公共路徑'public_path( '試驗/的test.xml')'。只是爲了確保'dd'這個代碼,並尋找路徑 - 如果它是正確的,這是你的答案。否則,祝你好運:) - 顯然,我以前的評論不會工作,我假設測試目錄與'app','config',...,'vendor'一起在根目錄下。 –

回答

1

流明沒有public_path(),你可能會熟悉Laravel輕鬆地抓取到公共文件的路徑。

重新實現它的最簡單方法是將一個名爲irazasyed/larasupport的程序包添加到項目中,該程序會添加各種缺失的幫助程序(包括public_path())以及添加Lumen缺少的vendor publish命令。

另外,如果你不希望添加第三方軟件包簡單地創建一個名爲helpers.php和你的應用程序目錄中的文件,然後你composer.json文件中添加以下的「自動載入」部分中,並運行composer dump-autoload刷新自動加載緩存:

"files": [ 
    "app/helpers.php" 
], 

然後內helpers.php添加以下內容:

<?php 
if (!function_exists('public_path')) { 
    /** 
    * Get the path to the public folder. 
    * 
    * @param string $path 
    * @return string 
    */ 
    function public_path($path = '') 
    { 
     return env('PUBLIC_PATH', base_path('public')) . ($path ? '/' . $path : $path); 
    } 
} 
+1

優秀的答案!我選擇了[irazasyed(https://packagist.org/packages/irazasyed/larasupport)解決方案,是我@ Zl3n意見 – Zl3n

+0

更安全,你怎麼知道它的安全?它可能使用相同的東西。我想這也幾乎是同樣的事情[這裏](https://github.com/irazasyed/larasupport/blob/master/src/helpers.php) –

+0

不記得爲什麼,但我現在對Laravel只工作 – Zl3n

2

你傳入的絕對路徑是相對於服務器的根目錄的功能。這不是URL的相同基本目錄。嘗試傳遞相對於當前執行腳本的路徑。