Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

parse_str

(PHP 3, PHP 4, PHP 5)

parse_str -- Разбирает строку в переменные

Description

void parse_str ( string str [, array arr] )

Разбирает строку str,которая должна иметь формат строки запроса URL и присваивает значения переменным в текущем контексте, если не передан второй аргумент arr. В последнем случае значения будкт сохранены в этой переменной как элементы массива.

Замечание: Поддержка необязательного второго аргумента была добавлена в PHP 4.0.3.

Замечание: Для получения текущей строки запроса (QUERY_STRING) может быть использована переменная $_SERVER['QUERY_STRING']. Также ознакомьтесь с разделом "Переменные вне PHP".

Пример 1. Использование parse_str()

<?php
$str
= "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo
$first// value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo
$output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

См. также описание функций parse_url(), pathinfo(), set_magic_quotes_runtime() и urldecode().



print> <ord
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
parse_str
chris at mcfadyen dot ca
31-Oct-2007 09:48
If you wish a version of parse_str sans magic quotes, the following will do the trick:

<?php
function parse_query($str) {
   
$pairs = explode('&', $str);

    foreach(
$pairs as $pair) {
        list(
$name, $value) = explode('=', $pair, 2);
        global $
$name;
        $
$name = $value;
    }
}
?>
miket3 at optonline dot net
30-Aug-2007 12:51
I saw some posts with people wondering
 why &'s are being
 sent to this function.  Well, basically
 because thats what comes
 from a QUERY_STRING. Anyway. The bug i found is
 that the first part of a query_string
 may not contain an &. Usually the
 first parameter comes directly after the ?.
So you
 might have to manually pre-pend an & to your
 query_string if one does not exist.

<?php
$base
="www.yahoo.com/search.aspx?";
$parsedurl=parse_url($base."&".rawurldecode($_SERVER
['QUERY_STRING']), PHP_URL_QUERY);
parse_str($parsedurl,$myquery);
$qbn = "n=".urlencode($myquery['n']);
?>

oh my god! to get this to post is ridiculous.
kermodebear at kermodebear dot org
08-Aug-2007 11:09
An old post from several years ago mentions that variable names cannot have a dot. They also cannot have a space. Spaces are automatically replaced with an underscore.

The following:
parse_str("My Value=Something", $result);

Will result in:
$result['My_Value'] = 'Something'

Although I understand why it is done, I still feel that this is unintuitive behavior.
Evan K
30-Jul-2007 07:43
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields.  If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');

# the above produces:
$foo = array('foo' => '3');
?>

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');

# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>

This can be confusing for anyone who's used to the CGI standard, so keep it in mind.  As an alternative, I use a "proper" querystring parser function:

<?php
function proper_parse_str($str) {
 
# result array
 
$arr = array();

 
# split on outer delimiter
 
$pairs = explode('&', $str);

 
# loop through each pair
 
foreach ($pairs as $i) {
   
# split into name and value
   
list($name,$value) = explode('=', $i, 2);
   
   
# if name already exists
   
if( isset($arr[$name]) ) {
     
# stick multiple values into an array
     
if( is_array($arr[$name]) ) {
       
$arr[$name][] = $value;
      }
      else {
       
$arr[$name] = array($arr[$name], $value);
      }
    }
   
# otherwise, simply stick it in a scalar
   
else {
     
$arr[$name] = $value;
    }
  }

 
# return result array
 
return $arr;
}

$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
Vladimir Kornea
17-Jul-2007 09:04
parse_str() is confused by ampersands (&) being encoded as HTML entities (&amp;). This is relevant if you're extracting your query string from an HTML page (scraping). The solution is to run the string through html_entity_decode() before running it through parse_str().

(Editors: my original comment was a caution whose solution is obvious, but it has resulted in three replies ("so what?" "as intended" and "this is how to fix it"). Please remove the previous four posts dealing with this (69529, 70234, 72745, 74818) and leave just the above summary. This issue is too trivial to warrant the number of comments it has received.)
Vladimir Kornea
17-Jul-2007 08:46
parse_str() contained a bug (#39763) in PHP 5.2.0 that caused it to apply magic quotes twice. This bug was marked as fixed in the release notes of PHP 5.2.1, but there were apparently some issues with getting the fix through CVS on time, as our install of PHP 5.2.1 was still affected by it.
arjan at archivision dot nl
05-Jul-2007 05:16
http_build_query() does that too.
mike dot coley at inbox dot com
02-Jun-2007 12:25
Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.

<?php

/* Converts an array of parameters into a query string to be appended to a URL.
 *
 * @return  string              : Query string to append to a URL.
 * @param   array    $array     : Array of parameters to append to the query string.
 * @param   string   $parent    : This should be left blank (it is used internally by the function).
 */
function append_params($array, $parent='')
{
   
$params = array();
    foreach (
$array as $k => $v)
    {
        if (
is_array($v))
           
$params[] = append_params($v, (empty($parent) ? urlencode($k) : $parent . '[' . urlencode($k) . ']'));
        else
           
$params[] = (!empty($parent) ? $parent . '[' . urlencode($k) . ']' : urlencode($k)) . '=' . urlencode($v);
    }

   
$sessid = session_id();
    if (!empty(
$parent) || empty($sessid))
        return
implode('&', $params);

   
// Append the session ID to the query string if we have to.
   
$sessname = session_name();
    if (
ini_get('session.use_cookies'))
    {
        if (!
ini_get('session.use_only_cookies') && (!isset($_COOKIE[$sessname]) || ($_COOKIE[$sessname] != $sessid)))
           
$params[] = $sessname . '=' . urlencode($sessid);
    }
    elseif (!
ini_get('session.use_only_cookies'))
       
$params[] = $sessname . '=' . urlencode($sessid);

    return
implode('&', $params);
}

?>

Note that the function will also append the session ID to the query string if it needs to be.
Michal Zalewski
28-Apr-2007 11:27
Vladimir Kornea:
Try use html_entity_decode()

$str = 'first=value&amp;arr[]=foo+bar&amp;arr[]=baz';
parse_str(html_entity_decode($str), $output);
print_r($output);

Array
(
    [first] => value
    [arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )

)
php at voodoolabs dot net
07-Mar-2007 12:32
This is probably a better solution than below. The first line makes sure the file doesn't exist then the second line directs all requests to a script. No need to output a 200 header with this method either.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php      [L]
lenix.de
10-Feb-2007 04:20
if you would like to get a nice url scheme with php/apache and and want to handle all requests in a central php script there's a simple solution/hack:

create a .htaccess in your "basedir" where you've got your main script (in this example index.php) containing some lines like:

"ErrorDocument 404 /index.php"

inside index.php you can now do

<?php
    $virtual_path
= substr(
       
$_SERVER['REQUEST_URI'],
       
strlen( dirname( $_SERVER['PHP_SELF'] ) ) + 1
   
);
    if( (
$pos = strpos( $virtual_path, '?' )) !== false ) {
       
parse_str( substr( $virtual_path, $pos + 1 ), $_GET );
       
$_REQUEST = array_merge( $_REQUEST, $_GET );
       
$virtual_path = substr( $virtual_path, 0, $pos );
    }

   
// some code checking for a valid location, etc...
   
header( 'HTTP/1.1 200 OK' );
   
header( 'Content-Type: text/plain' );

    echo
$virtual_path."\n\n";
   
print_r( $_REQUEST );
?>

// guido 'lenix' boehm
jgbreezer at gmail dot com
31-Jan-2007 04:52
Vladimir Kornea wrote on 8 Sep 2006:
"This function is confused by ampersands (&) being encoded as HTML entities (&amp;)"

Well, it would be - it's not supposed to be passed html entities, that's a different encoding scheme. This function does correctly decode url encoded params for you though (with the rawurlencode rather than urlencode, ie '+' is translated to a space).
Olivier Mengu
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571