通過使用 CodeIgniter 4 框架,我開發了RESTful api,我需要訪問檔案(.json 和 .txt)來獲取內容。但無法訪問 php 內置函式 file_get_contents()。有關更多詳細資訊,請查看隨附的螢屏截圖 API_curl_file_get_content_error.PNG

并且 test.txt 檔案也可以通過相同的檔案路徑訪問。有關更多詳細資訊,請檢查螢屏截圖 Input-txt-file-content.png

注意: 1)test.txt 檔案和相應的目錄具有完全權限。2)開發環境: <---->Apache/2.4.47 (Win64) OpenSSL/1.1.1k PHP/8.1.2 <---->資料庫客戶端版本:libmysql - mysqlnd 8.1.2 <---- >PHP 版本:8.1.2 <----> CodeIgniter 4
Product.php(索引方法)
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
class Product extends ResourceController
{
use \CodeIgniter\API\ResponseTrait;
public function index()
{
helper("filesystem");
ini_set('max_execution_time', 300);
$data['msg'] = "Product Index wizard";
$data['status'] = 200;
$file_path = base_url() . '/assets/data/test.txt'; // Read JSON
$json = file_get_contents($file_path, true);
$json_data = json_decode($json, true);
return $this->respond($data);
}
}
uj5u.com熱心網友回復:
解釋:
請記住,“http://localhost:8085/”很可能指向專案的檔案根目錄,通常是/public路徑。因此,除非“ assets ”檔案夾駐留在/public路徑中,file_get_contents("http://localhost:8085/assets/data/test.txt");否則將無法找到請求的服務器資源。
解決方案:
由于您的檔案資源 ( test.txt ) 在本地檔案系統上,
代替:
file_get_contents("http://localhost:8085/assets/data/test.txt");
使用這個:
常量ROOTPATH
專案根目錄的路徑。就在APPPATH上方。
file_get_contents(ROOTPATH . "assets/data/test.txt");
附錄:
我相信您也忘記將輸出添加到資源控制器方法中$json_data的回傳$data變數中。Product::index
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/440907.html
