Skip to content

[WordPress] 使用 file_get_contents() 讀取文件

在使用 PHP 開發 WordPress 外掛(plugin)的過程中,我們總少不了開檔、將檔案讀取進來的動作。而在這之中,以 file_get_contents() 最為常見。


file_get_contents() 介紹

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )


  • $filename:文件路徑(可為 URL)
  • $use_include_path:是否使用 php.ini 中的 include_path 尋找
  • $context: 資源流上下文
  • $offset: 起始位置
  • $maxlen:長度

使用方法

基本上使用方法如下:

$text = file_get_contents( "FILE_PATH" );
echo $text;


便可印出該份文件。如果在外掛檔案中你想要使用相對位置來讀取,可以使用魔法常數 DIR 來取得當前目錄位置。以此加上相對位置,便可以輕鬆取得部署上網站後該文件的位置。

$text = file_get_contents( "FILE_PATH" );
echo $text;

References


Read More

Leave a Reply