php array to url params

PHP url to array

I have these urls from a web log:

How can I convert this URL in an array in PHPso i will have an array like this

then later I can loop to that array to find duplicates or validate the information correctly.

6 Answers 6

PHP has a native function for that, the parse_str function. You can use it like:

This will do just what you need.

php array to url params. Смотреть фото php array to url params. Смотреть картинку php array to url params. Картинка про php array to url params. Фото php array to url params

There may be a better way to do this but this is what I came up with.

With parse_url() you can parse the URL to an associative array. In the result array you get amongst others the query part. Then you can use parse_str() for parsing the query part to your new array.

php array to url params. Смотреть фото php array to url params. Смотреть картинку php array to url params. Картинка про php array to url params. Фото php array to url params

php array to url params. Смотреть фото php array to url params. Смотреть картинку php array to url params. Картинка про php array to url params. Фото php array to url params

Use parse_url function like

Which will give you the following array output

And from the query you can easily split it as to (key,value) paira. Hope this helps.:)

php array to url params. Смотреть фото php array to url params. Смотреть картинку php array to url params. Картинка про php array to url params. Фото php array to url params

Not the answer you’re looking for? Browse other questions tagged php arrays url or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

http_build_query

http_build_query — Генерирует URL-кодированную строку запроса

Описание

Генерирует URL-кодированную строку запроса из предоставленного ассоциативного (или индексированного) массива.

Список параметров

Может быть массив или объект, содержащий свойства.

Если data массив, то он может быть простой одномерной структурой или массивом массивов (который, в свою очередь, может содержать другие массивы).

Если data объект, тогда только общедоступные свойства будут включены в результат.

Если числовые индексы используются в базовом массиве и этот параметр указан, то он будет добавлен к числовому индексу для элементов только в базовом массиве.

Это позволяет обеспечить допустимые имена переменных, в которые позже данные будут декодированы PHP или другим CGI-приложением.

arg_separator.output используется в качестве разделителя аргументов, но может быть переопределён путём указания этого параметра.

Возвращаемые значения

Возвращает URL-кодированную строку.

Примеры

Пример #1 Простой пример использования http_build_query()

Результат выполнения данного примера:

Пример #2 Пример использования http_build_query() с числовыми индексами элементов.

Результат выполнения данного примера:

Пример #3 Пример использования http_build_query() с многомерными массивами

Результат выполнения данных примеров: (символы перенесены для удобства чтения)

Только числовой индексированный элемент «CEO» в базовом массиве получил префикс. Другие числовые индексы, найденные в pastimes, не требуют строкового префикса, чтобы быть допустимыми именами переменных.

Пример #4 Пример использования http_build_query() с объектом

$parent = new parentClass ();

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 24 notes

Params with null value do not present in result string.

If you need to change the enc_type, use this:

http_build_query($query, null, ini_get(‘arg_separator.output’), PHP_QUERY_RFC3986);

// BAD CODE!
http_build_query($query, null, null, PHP_QUERY_RFC3986);

if you send boolean values it transform in integer :

$a = [teste1= true,teste2=false];
echo http_build_query($a)

//result will be teste1=1&teste2=0

This function makes like this

To do it like this:

As noted before, with php5.3 the separator is & on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.

But if you post to a tomcat java server or something else the & might not be handled properly.

To overcome this specify:

http_build_query($array); //gives & to some servers

It’s not mentioned in the documentation, but when calling http_build_query on an object, public null fields are ignored.

Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.

$post_data = array(‘name’=>’miller’, ‘address’=>array(‘address_lines’=>array()), ‘age’=>23);
echo http_build_query($post_data);

Instead you can make your own simple function if you simply want to pass along the data:

If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following.

Источник

parse_str

(PHP 4, PHP 5, PHP 7, PHP 8)

parse_str — Parses the string into variables

Description

Parses string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).

Parameters

If the second parameter result is present, variables are stored in this variable as array elements instead.

Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.

Return Values

No value is returned.

Changelog

VersionDescription
8.0.0result is no longer optional.
7.2.0Usage of parse_str() without a second parameter now emits an E_DEPRECATED notice.

Examples

Example #1 Using parse_str()

Because variables in PHP can’t have dots and spaces in their names, those are converted to underscores. Same applies to naming of respective key names in case of using this function with result parameter.

Example #2 parse_str() name mangling

Notes

All variables created (or values returned into array if second parameter is set) are already urldecode() d.

See Also

User Contributed Notes 31 notes

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:

# 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.

# bizarre php-specific behavior
parse_str ( ‘foo[]=1&foo[]=2&foo[]=3’ );

if you need custom arg separator, you can use this function. it returns parsed query as associative array.

You may want to parse the query string into an array.

As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.

This is a very useful combination if you want to re-use a search string url, but also slightly modify it:

Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest

(Array indexes are automatically created.)

CONVERT ANY FORMATTED STRING INTO VARIABLES

I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:

to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character. and i have comma separated values. so i replace comma with &

Note that the characters «.» and » » (empty space) will be converted to «_». The characters «[» and «]» have special meaning: They represent arrays but there seems to be some weird behaviour, which I don’t really understand:

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.

?>

Note that the function will also append the session ID to the query string if it needs to be.

The array to be populated does not need to be defined before calling the function:

Источник

parse_url

(PHP 4, PHP 5, PHP 7, PHP 8)

parse_url — Parse a URL and return its components

Description

This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial and invalid URLs are also accepted, parse_url() tries its best to parse them correctly.

Parameters

Return Values

Examples

Example #1 A parse_url() example

The above example will output:

Example #2 A parse_url() example with missing scheme

The above example will output:

Notes

This function may not give correct results for relative URLs.

This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP’s backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///. ) are allowed. For any other scheme this is invalid.

See Also

User Contributed Notes 33 notes

[If you haven’t yet] been able to find a simple conversion back to string from a parsed url, here’s an example:

Here is utf-8 compatible parse_url() replacement function based on «laszlo dot janszky at gmail dot com» work. Original incorrectly handled URLs with user:pass. Also made PHP 5.5 compatible (got rid of now deprecated regex /e modifier).

Here’s a good way to using parse_url () gets the youtube link.
This function I used in many works:

I was writing unit tests and needed to cause this function to kick out an error and return FALSE in order to test a specific execution path. If anyone else needs to force a failure, the following inputs will work:

There’s a quirk where this function will return the host as the «path» if there is a leading space.

I have coded a function which converts relative URL to absolute URL for a project of mine. Considering I could not find it elsewhere, I figured I would post it here.

The following function takes in 2 parameters, the first parameter is the URL you want to convert from relative to absolute, and the second parameter is a sample of the absolute URL.

Currently it does not resolve ‘../’ in the URL, only because I do not need it. Most webservers will resolve this for you. If you want it to resolve the ‘../’ in the path, it just takes minor modifications.

?>

OUTPUTS:
http :// user:pass@example.com:8080/path/to/index.html
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/img.gif
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/path/to/../img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/images/img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/path/to/../images/img.gif

Sorry if the above code is not your style, or if you see it as «messy» or you think there is a better way to do it. I removed as much of the white space as possible.

Источник

Передача массивов в качестве параметра url

Каков наилучший способ передать массив как параметр url? Я думал, если это возможно:

Я читал примеры, но я нахожу это беспорядочным:

ОТВЕТЫ

Ответ 1

Ответ 2

Изменить: Не пропустите решение Stefan выше, в котором используется очень удобная функция http_build_query() : fooobar.com/questions/69545/.

knittl находится прямо на побеге. Однако есть более простой способ сделать это:

Если вы хотите сделать это с помощью ассоциативного массива, попробуйте это вместо:

PHP 5.3 + (функция лямбда)

Ответ 3

Эта переменная может быть восстановлена ​​с помощью unserialize

Итак, переходя к URL-адресу, который вы используете:

и для восстановления используемой переменной

Будьте осторожны. Максимальный размер запроса GET ограничен 4k, что вы можете легко преодолеть, передав массивы в URL.

Кроме того, это действительно не самый безопасный способ передачи данных! Вероятно, вам следует изучить использование сеансов.

Ответ 4

пожалуйста, избегайте переменные при выводе ( urlencode ).

и вы не можете просто напечатать массив, вам нужно построить свой url, используя какой-то цикл.

Ответ 5

Ответ 6

Ответ 7

Это не прямой ответ, так как об этом уже был дан ответ, но все говорили о передаче данных, но никто не сказал, что вы делаете, когда он туда доберется, и мне понадобилось полчаса, чтобы работать вне. Поэтому я подумал, что помогу здесь.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *