Home  >  Article  >  Backend Development  >  How to convert array into url in php

How to convert array into url in php

PHPz
PHPzOriginal
2023-04-18 14:07:09598browse

With the continuous development of the Internet, we rely more and more on the network to transmit and exchange data. Whether browsing the web, doing e-commerce or making online payments, we all need to use URLs to transmit and obtain necessary information.

In PHP, we often need to convert arrays into URLs for passing and processing through URL parameters. In this article, we will explain how to convert a PHP array to a URL and provide practical example code for reference.

Conversion method

In PHP, we can use the http_build_query() function to convert the array into URL format. The http_build_query() function converts the array to URL encoding, generating a string containing all parameter key-value pairs. The following is the syntax of the http_build_query() function:

string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

This function has four parameters:

  • query_data: required parameter, the data to be converted to URL can be an associative array .
  • numeric_prefix: Optional parameter, if this parameter is set to true, it will automatically add a prefix to the key name. By default, the prefix is ​​"parameters[]".
  • arg_separator: Optional parameter, the separator between parameters, the default value is "&".
  • enc_type: Optional parameter, encoding type, default is PHP_QUERY_RFC1738. If this parameter is set to PHP_QUERY_RFC3986, the RFC3986 encoding type will be used.

Sample code

Here is a code example to convert an array to a URL:

 'myusername',
    'password' => 'mypassword',
    'city' => 'New York',
    'state' => 'NY',
);

$url_parameters = http_build_query($parameters);

$url = 'http://www.example.com/login?' . $url_parameters;

echo $url;
?>

In this example, we define an associative array $parameters, where Contains some key-value pairs. Then, we use the http_build_query() function to convert the array into a URL-encoded string and save it to the $url_parameters variable.

Finally, we add $url_parameters to the URL, generate the final URL, and use the echo function to output it to the screen.

Output result:

http://www.example.com/login?username=myusername&password=mypassword&city=New+York&state=NY

This is one of the most basic methods to convert a PHP array into a URL.

Extension Application

Now we have seen how to convert a PHP array into a URL. Next, we'll cover some more advanced uses to help you better understand its applications.

  1. Prefix

We can use the second parameter numeric_prefix to add a prefix to the parameter name. The following example prefixes the parameter names in the array with "data[ ]".

 'foo',
    2 => 'bar',
    3 => 'faz'
);

$query = http_build_query($data, 'data[]');

echo $query;
?>

Output result:

data%5B%5D=foo&data%5B%5D=bar&data%5B%5D=faz
  1. urlencode()

If you want more control over the parameters in the URL, before generating the URL, you can use The urlencode() function encodes parameter values. For example:

 'myusername',
    'password' => 'mypassword',
    'city' => urlencode('New York'),
    'state' => urlencode('NY'),
);

$url_parameters = http_build_query($parameters);

$url = 'http://www.example.com/login?' . $url_parameters;

echo $url;
?>

In this example, we use the urlencode() function to encode "New York" and "NY" to ensure that no illegal characters appear in the URL. The final URL will look like this:

http://www.example.com/login?username=myusername&password=mypassword&city=New+York&state=NY
  1. Advanced Array

If your array contains multidimensional subarrays, you can use recursion to convert the entire array into a URL. For example:

 'myusername',
    'password' => 'mypassword',
    'address' => array(
        'city' => 'New York',
        'state' => 'NY',
        'zip' => '10001'
    )
);

function build_query_string_recursive(array $array, $prefix = null) {

    $query = array();

    foreach($array as $key => $value) {
        $new_key = is_null($prefix) ? $key : sprintf('%s[%s]', $prefix, $key);

        if(is_array($value)) {
            $query[] = build_query_string_recursive($value, $new_key);
        } else {
            $query[] = sprintf('%s=%s', urlencode($new_key), urlencode($value));
        }
    }

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

$url_parameters = build_query_string_recursive($parameters);

$url = 'http://www.example.com/login?' . $url_parameters;

echo $url;
?>

In this example, we use the build_query_string_recursive() function to convert the entire array into a URL. This function uses recursion to process multi-dimensional arrays, ensuring that all key-value pairs are correctly converted to URL-encoded format.

Finally, we add $url_parameters to the URL, generate the final URL, and use the echo function to output it to the screen.

Output results:

http://www.example.com/login?username=myusername&password=mypassword&address[city]=New+York&address[state]=NY&address[zip]=10001

Conclusion

Converting PHP arrays to URLs is a very useful trick for passing and processing data. In this article, we introduce the http_build_query() function with some practical examples for reference.

Whether you need to convert a simple array or a multidimensional array into a URL, these examples can help you complete the task successfully. Thank you for reading, I hope this article is helpful!

The above is the detailed content of How to convert array into url in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn