如何用PHP CURL发送JSON POST数据并解析指定URL的JSON数据?
Alright, let's walk through exactly how to send a JSON-formatted POST request using PHP cURL, then parse the response from that Openbravo JSON REST endpoint you provided. I'll include full code with comments, plus examples of extracting the specific data from your sample response.
Step 1: Prepare Your JSON POST Payload
First, structure the data you want to send as a PHP array, then encode it to a JSON string. For a BusinessPartner endpoint, this might look like (adjust fields based on your actual requirements):
// Sample POST data (match Openbravo's expected schema) $postData = [ 'entityName' => 'BusinessPartner', 'data' => [ '_identifier' => 'New Test Partner', 'client' => '23C59575B9CF467C9620760EB255B389', 'organization' => '2E60544D37534C0B89E765FE29BC0B43' // Add other required fields here ] ]; // Encode array to JSON string $jsonPayload = json_encode($postData);
Step 2: Configure & Execute cURL Request
Next, set up the cURL handle with all necessary options to send the JSON POST request to your target URL:
// Target API endpoint $apiUrl = 'http://demoerp.rawntech.com/demoerp/org.openbravo.service.json.jsonrest/BusinessPartner'; // Initialize cURL $ch = curl_init($apiUrl); // Set cURL options curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $jsonPayload, // Set content type header to JSON CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'Content-Length: ' . strlen($jsonPayload) ], // Return response instead of printing it CURLOPT_RETURNTRANSFER => true, // Optional: Disable SSL verification if needed (not recommended for production) // CURLOPT_SSL_VERIFYPEER => false, // CURLOPT_SSL_VERIFYHOST => false ]); // Execute the request and get the response $response = curl_exec($ch); // Check for cURL errors if(curl_errno($ch)) { throw new Exception('cURL Error: ' . curl_error($ch)); } // Close cURL handle curl_close($ch);
Step 3: Parse the JSON Response
Now that you have the raw response string, decode it into a PHP array/object and extract the data you need. Using your sample response, here's how to access the BusinessPartner details:
// Decode JSON response to associative array $responseData = json_decode($response, true); // Check if JSON decoding failed if(json_last_error() !== JSON_ERROR_NONE) { throw new Exception('JSON Decode Error: ' . json_last_error_msg()); } // Access the "data" array from the response if(isset($responseData['response']['data']) && is_array($responseData['response']['data'])) { foreach($responseData['response']['data'] as $partner) { // Extract specific fields from each BusinessPartner echo "Partner ID: " . $partner['id'] . "<br>"; echo "Identifier: " . $partner['_identifier'] . "<br>"; echo "Entity Name: " . $partner['_entityName'] . "<br>"; echo "Client Identifier: " . $partner['client$_identifier'] . "<br>"; echo "Organization ID: " . $partner['organization'] . "<br><br>"; } } else { echo "No BusinessPartner data found in response."; }
Key Notes:
- Authentication: If the Openbravo API requires authentication (like API keys or OAuth), add the appropriate headers (e.g.,
Authorization: Bearer YOUR_TOKEN) to theCURLOPT_HTTPHEADERarray. - Production Best Practices: Never disable SSL verification in production—ensure your server has valid SSL certificates installed.
- Error Handling: The code includes basic error handling for cURL and JSON decoding; expand this to fit your app's needs (e.g., logging, custom error responses).
内容的提问来源于stack exchange,提问作者RK-Rohan

