Home >Backend Development >PHP Problem >How to put array in URL and transmit it in php
In PHP, you can use arrays to store a set of data and pass the data to other pages or systems in a certain format. Putting the array in the URL and transmitting it is a common way.
Transmitting the array in the URL can be achieved in the following two ways:
<?php // 将数组进行序列化,结果是一个字符串 $data = array('name'=>'张三', 'age'=>18, 'sex'=>'男'); $queryString = http_build_query($data); // 假设当前页面的url是http://www.example.com/test.php,将序列化后的字符串追加在url的末尾即可 $url = 'http://www.example.com/test.php?' . $queryString; echo $url; // 输出结果:http://www.example.com/test.php?name=%E5%BC%A0%E4%B8%89&age=18&sex=%E7%94%B7 ?>In the above example, we used the
http_build_query() function to serialize the array. This function converts an array into a URL-encoded string. At the same time, we append the serialized string to the end of the URL of the current page to generate a new URL.
$_GETSuper global variable:
<?php // test.php print_r($_GET); // 输出结果:Array ( [name] => 张三 [age] => 18 [sex] => 男 ) ?>In the above code, we use
$_GET The super global variable obtains the data in the URL and uses the
print_r() function to print out the data.
<?php // 创建一个数组 $data = array('name'=>'张三', 'age'=>18, 'sex'=>'男'); // 初始化CURL,设置请求的URL、请求方式、请求体等参数 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/test.php'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 执行请求并获取响应内容 $response = curl_exec($ch); curl_close($ch); echo $response; ?>In the above example, we used the cURL library to send the POST request and directly placed the array in the request body. On the server side, we can use the
$_POST super global variable to obtain the data transmitted by the POST request:
<?php // test.php print_r($_POST); // 输出结果:Array ( [name] => 张三 [age] => 18 [sex] => 男 ) ?>In the above code, we use the
$_POST super global variable The variable obtains the data transmitted by the POST request and uses the
print_r() function to print out the data.
The above is the detailed content of How to put array in URL and transmit it in php. For more information, please follow other related articles on the PHP Chinese website!