用 php 讀檔案的範例

想吃燒肉
3 min readJan 20, 2021

--

到底要投資什麼才能賺好賺飽呢? 你還是投資自己吧

最近想要一些工具可以自動讀檔案,想說都在寫 js ,想用不同的語言來試試看,那就決定是你了 「PHP」!

那我的目標就是

  1. 讀取整個目錄
  2. 讀取裡面的檔案資料
  3. 根據資料做整理,變成我要的形狀

#讀取目錄的寫法 (scandir

$dir = "./models/";    // 我想要讀取的目錄為 ./models/
$file = scandir($dir);
print_r($file); // 回來是陣列

#一行一行讀取裡面的檔案內容 (fopen, feof, fgets, fclose)

$file_path = "./models/fundAllocationMapping.js";
$file = fopen($file_path, "r");
$result = array();
$i = 0;
while (!feof($file)) {
$result[$i] = fgets($file); // fgets()函式從檔案指標中讀取一行
$i++;
}
fclose($file);
$result = array_filter($result);
print_r($result);

#取得我想要的資料(strpos)

$str = '123456';
if (strpos($str, '123') !== false) {
echo "str 字串包含 123";
} else {
echo "str 字串不包含 123";
}

組合起來:

我想要取得那行包含有 「: {」以及 「belongsTo」「hasOne」「hasMany」的字串

<?php
$dir = "./models/";
$file = scandir($dir);

foreach ($file as $key => $value) {
if ($key > 1) {
$file_path = "./models/$value";
$file = fopen($file_path, "r");
$i = 0;
echo ("$value \n");
while (!feof($file)) {
$result[$i] = fgets($file); //fgets()函式從檔案指標中讀取一行
if (strpos($result[$i], ': {') !== false &&
strpos($result[$i], 'hooks') === false) {
echo $result[$i];
}
if (strpos($result[$i], 'belongsTo') !== false) {
echo $result[$i];
}
if (strpos($result[$i], 'hasOne') !== false) {
echo $result[$i];
}
if (strpos($result[$i], 'hasMany') !== false) {
echo $result[$i];
}
$i++;
}
fclose($file);
$result = array_filter($result);
// print_r($result);
}
}

搞定!

--

--

想吃燒肉
想吃燒肉

Written by 想吃燒肉

我喜歡燒肉,只是個宅男, Web 前後端略懂,歡迎大家跟我討論。

No responses yet