如何将指定CURL请求转为PHP代码?含认证与参数处理疑问
Hey Mike, let's break down how to convert that curl command into working PHP code, addressing both the authentication and JSON payload parts you're unsure about:
1. HTTP Basic Authentication in PHP cURL
The -u "<brugernavn>:<password>" in your curl command uses HTTP Basic Authentication. In PHP's cURL extension, you don't need to manually encode the credentials—you can use the CURLOPT_USERPWD option to pass the username:password string directly, and cURL will handle the base64 encoding for you automatically.
2. Sending the JSON Request Body
Your curl command sends a JSON payload with -d '{"from":0,...}'. To replicate this in PHP:
- First, define your query as a PHP array (way easier to maintain than raw JSON strings)
- Convert it to a valid JSON string with
json_encode() - Set the
Content-Typeheader toapplication/jsonso the API knows to parse the payload as JSON - Pass the JSON string to
CURLOPT_POSTFIELDS(important: don't pass an array here, as that would send form-data instead of raw JSON)
Complete requestApiV2 Method Example
function requestApiV2($cvrNumber, $username, $password) { // API endpoint URL $url = 'http://distribution.virk.dk/cvr-permanent/_search'; // Initialize cURL session $ch = curl_init($url); // Set up the query as a PHP array $query = [ 'from' => 0, 'size' => 1, 'query' => [ 'term' => [ 'cvrNummer' => $cvrNumber ] ] ]; // Convert array to JSON string $jsonPayload = json_encode($query); // Configure cURL options curl_setopt_array($ch, [ // Enable POST request CURLOPT_POST => true, // Attach the JSON payload CURLOPT_POSTFIELDS => $jsonPayload, // Return response as string instead of outputting it CURLOPT_RETURNTRANSFER => true, // Set Basic Auth credentials CURLOPT_USERPWD => "$username:$password", // Set required request headers CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'Content-Length: ' . strlen($jsonPayload) // Optional but helpful for some APIs ], // Disable SSL verification only for HTTP endpoints (remove this if using HTTPS!) CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false ]); // Execute the request $response = curl_exec($ch); // Handle cURL errors if(curl_errno($ch)) { $errorMsg = curl_error($ch); curl_close($ch); throw new Exception("cURL Error: $errorMsg"); } // Get HTTP status code for debugging $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Clean up the cURL session curl_close($ch); // Convert JSON response back to PHP array $result = json_decode($response, true); return [ 'status_code' => $httpStatusCode, 'data' => $result ]; }
Quick Testing Tips (Even Without Credentials)
If you don't have the username/password yet, you can:
- Temporarily comment out the
CURLOPT_USERPWDline and addCURLOPT_VERBOSE => trueto see full request details (headers, payload) in your error log - Compare the PHP-generated request with your original curl command using verbose mode (
curl -v ...) to ensure they match
内容的提问来源于stack exchange,提问作者Mike Nor
相关产品推荐
相关产品推荐

