我想實作讀取和列印不帶 .php URL 擴展名的 JSON 資料。但是服務器回傳錯誤。
我的 PHP 代碼(data.php)如下:
<?php
// GET FULL PAGE URL
$link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// GET EVRYHING AFTER THE LAST SLASH
$params = substr($link, strrpos($link, '/') 1);
// PASS THE PARAMETERS TO API
$url = "http://api.plos.org/$params";
//read json file from url in php
$readJSONFile = file_get_contents($url);
header('Content-Type: application/json'); //
print_r($readJSONFile); // display contents
.htaccess 檔案,用于洗掉 .php 擴展名
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
如果我在沒有 .php 擴展名的情況下嘗試使用 .php 擴展名( https://local.test/data.php/search?q=title:DNA )訪問時,我將獲得正確的資料,它回傳 404錯誤。 https://local.test/data/search?q=title:DNA
uj5u.com熱心網友回復:
您可以嘗試使用以下方法更改.htaccess檔案內容:
RewriteEngine On
RewriteBase /
RewriteRule ^data/search$ data.php [L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . index.php [L]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456033.html
