When sending get request to third party server, you need to add query string of data into url. Some request accept request to text format, means you need to pass data into url query string. You may already have PHP array or object which you want to pass as payload. In this situation, you need to convert array or object into query string.
In this article, we will show you how you can convert array into query string. PHP has built-in function http_build_query which convert array or object into URL-encoded query string.
http_build_query($data, $numeric_prefix, $separator, $encoding);
$data required array or object which you want to convert
$numeric_prefix optional string prefix on numeric key
$separator optional parameter seperator instead of default &
$encoding optional encoding type default PHP_QUERY_RFC1738
<?php
$user = [
'name' => 'Harsukh Makwana',
'email' => '[email protected]',
'twitter' => 'harsukh21',
'github' => 'harsukh21'
];
$data = http_build_query($user);
echo($data); // name=Harsukh+Makwana&email=harsukh21%40gmail.com&twitter=harsukh21&github=harsukh21
If you need indexed array to be query string with prefixed or comma seperated string, here is the example:
<?php
$user = [
'1' => 'Harsukh Makwana',
'2' => '[email protected]',
'3' => 'harsukh21',
'4' => 'harsukh21'
];
$data = http_build_query($user, 'param_', ',');
echo($data); // param_1=Harsukh+Makwana,param_2=harsukh21%40gmail.com,param_3=harsukh21,param_4=harsukh21
If you want to use your own custom logic or working on PHP 4, here is the custom function to do same result as above:
<?php
$user = [
'name' => 'Harsukh Makwana',
'email' => '[email protected]',
'twitter' => 'harsukh21',
'github' => 'harsukh21'
];
/**
* Builds an http query string
*
* @param array
* @return string
*/
function httpbuildQuery($query, $seperator = '&') {
$query_array = [];
foreach($query as $key => $key_value) {
$query_array[] = urlencode($key) . '=' . urlencode($key_value);
}
return implode($seperator, $query_array);
}
$data = httpbuildQuery($user);
echo($data); // name=Harsukh+Makwana&email=harsukh21%40gmail.com&twitter=harsukh21&github=harsukh21
I hope it will help you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to convert URL to array in PHP
An URL is the string of many data. URL c...Laravel Blade Section Directive Example
Laravel provides many built-in directive...How to Validate Textbox to Accept only Characters in Javascript
In this article, we will see how to allo...CRUD with Image Upload in Laravel 8 Example
In this tutorial we will go over the dem...How to insert HTML content into an iFrame using jQuery
Use the jQuery contents() method You...