如何从PHP中的URL获取多个同名参数 [英] How to get multiple parameters with same name from a URL in PHP

查看:30
本文介绍了如何从PHP中的URL获取多个同名参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a PHP application that will on occasion have to handle URLs where more than one parameter in the URL will have the same name. Is there an easy way to retrieve all the values for a given key? PHP $_GET returns only the last value.

具体来说,我的应用程序是一个 OpenURL 解析器,可能会获取如下 URL 参数:

To make this concrete, my application is an OpenURL resolver, and may get URL parameters like this:

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

(是的,我知道这很丑,欢迎来到我的世界).请注意,键rft_id"出现了两次:

(Yes, I know it's ugly, welcome to my world). Note that the key "rft_id" appears twice:

  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代码>) 已被覆盖.

$_GET will return just http://www.biodiversitylibrary.org/bibliography/4323, the earlier value (info:oclcnum/1903126) having been overwritten.

我想访问这两个值.这在 PHP 中可能吗?如果没有,对如何处理这个问题有什么想法吗?

I'd like to get access to both values. Is this possible in PHP? If not, any thoughts on how to handle this problem?

推荐答案

类似:

$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 参数总是有可能重复的,所以最好总是有数组,而不是只为那些你期望它们的参数.

Since it's always possible that one URL parameter is repeated, it's better to always have arrays, instead of only for those parameters where you anticipate them.

这篇关于如何从PHP中的URL获取多个同名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆