php - 如何从PHP中的URL获取多个同名参数

标签 php url parameters

我有一个 PHP 应用程序,有时必须处理 URL,其中 URL 中的多个参数具有相同的名称。有没有一种简单的方法来检索给定键的所有值? PHP $_GET 只返回最后一个值。

为了具体说明,我的应用程序是一个 OpenURL 解析器,并且可能会像这样获取 URL 参数:

ctx_ver=Z39.88-2004
&rft_id=info:oclcnum/1903126
&rft_id=http://www.biodiversitylibrary.org/bibliography/4323
&rft_val_fmt=info:ofi/fmt:kev:mtx:book
&rft.genre=book
&rft.btitle=At last: a Christmas in the West Indies. 
&rft.place=London,
&rft.pub=Macmillan and co.,
&rft.aufirst=Charles
&rft.aulast=Kingsley
&rft.au=Kingsley, Charles,
&rft.pages=1-352
&rft.tpages=352
&rft.date=1871

(是的,我知道它很丑,欢迎来到我的世界)。请注意, key “rft_id”出现了两次:

  1. rft_id=info:oclcnum/1903126
  2. rft_id=http://www.biodiversitylibrary.org/bibliography/4323

$_GET 将只返回 http://www.biodiversitylibrary.org/bibliography/4323,较早的值 (info:oclcnum/1903126) 已被覆盖。

我想访问这两个值。这在 PHP 中可行吗?如果没有,关于如何处理这个问题有什么想法吗?

最佳答案

类似:

$query  = explode('&', $_SERVER['QUERY_STRING']);
$params = array();

foreach( $query as $param )
{
  // prevent notice on explode() if $param has no '='
  if (strpos($param, '=') === false) $param += '=';

  list($name, $value) = explode('=', $param, 2);
  $params[urldecode($name)][] = urldecode($value);
}

给你:

array(
  'ctx_ver'     => array('Z39.88-2004'),
  'rft_id'      => array('info:oclcnum/1903126', 'http://www.biodiversitylibrary.org/bibliography/4323'),
  'rft_val_fmt' => array('info:ofi/fmt:kev:mtx:book'),
  'rft.genre'   => array('book'),
  'rft.btitle'  => array('At last: a Christmas in the West Indies.'),
  'rft.place'   => array('London'),
  'rft.pub'     => array('Macmillan and co.'),
  'rft.aufirst' => array('Charles'),
  'rft.aulast'  => array('Kingsley'),
  'rft.au'      => array('Kingsley, Charles'),
  'rft.pages'   => array('1-352'),
  'rft.tpages'  => array('352'),
  'rft.date'    => array('1871')
)

由于总是有可能重复一个 URL 参数,因此最好始终使用数组,而不是仅针对您预期的那些参数。

关于php - 如何从PHP中的URL获取多个同名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/353379/

相关文章:

php - MySQL 编辑值

php - 使用 Ajax 和 Jquery 上传文件

php - Ajax 无法与 wpdb 一起使用

Android:点击按钮时转到 HTTP 网址

asp.net - http post请求在ASP NET MVC中将参数转换为 'Null'

templates - Grails:如何将参数从自定义标记库传递到模板?

php - Curl上传文件失败

security - 如何保护 Amazon S3 URL

html - 这个网址有什么问题?

python - 我如何将 gdal_grid 与点一起使用