首页 > 解决方案 > 从 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 有什么区别,我该如何恢复?

标签: phpurl

解决方案


你可以试试这样的

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

希望这就是你要找的。


推荐阅读