php - 从 URL 检索信息
问题描述
我正在使用 PHP 创建一个 API,但在使用 URL 时遇到了困难,它会将这个 URL 发送给我http://localhost/api/index/Peoples/3
我的想法是我想使用 Peoples 类,并且我想获得代码为 3 的 Person,有什么方法可以让 Peoples 和数字 3 获得吗?
我的想法是这样的,我从浏览器中检索 URL,然后我将对其进行爆炸。虽然我不需要通过 url 传递参数,但这完美地工作
public function getClass(){
$params = explode("/api/index/", $this->currentUrl);
if(count($params) == 1)
return "no have class !";
else
{
$params = explode('/', $params[1]);
$this->callClass($params[0]);
return "Classe : ".$params[0];
}
}
使用此代码,我可以恢复 Peoples,然后知道我将使用哪个类。现在我想传递代码的参数,例如 3。我可以传递如下 ../Peoples?id=3 但我必须打破更多的字符串,有更好的方法吗?
通过 ../Peoples?id=3 或 ../Peoples/3 有什么区别,我该如何恢复?
解决方案
你可以试试这样的
public function getClass()
{
$path = explode('/', parse_url($this->currentUrl, PHP_URL_PATH));
if(count($path) !== 5){
return 'not valid url';
}
$id = array_pop($path);
$class = array_pop($path);
//$this->callClass($class);
$newPath = $class.'?id='.$id;
return $newPath;
}
关于您关于 /Peoples?id=3 或 ../Peoples/3 的问题,如果您正在使用诸如 symfony 或 laravel 之类的框架,您可以在其中定义控制器,而第一个可以轻松获取数据,则第二个更容易从带有 $_GET['id'] 的 URL
希望这就是你要找的。
推荐阅读
- file - 使用 SharePlum for Sharepoint 下载文件
- linux - 如果匹配显示成功或失败,如何匹配文件中的语法
- javascript - 使用自动换行在 React 中渲染逗号分隔的链接
- c++ - 为什么我得到 nan 作为下面代码的输出?
- c++ - C++:模板的 IntelliSense 失败
- python - 如何将数组从.txt文件解析为python DataFrame
- python - 我有一个 txt 文件,我想创建一个数组
- html - 行为不端的页脚
- java - 在drools-java中收集为哈希/映射键值对
- c++ - Qt C++ SerialPort 未接收数据