PHP数据库集成:从XML节点提取值并添加至数组的问题
Hey there! Let's break this down step by step—since you already can pull the needed values from the source XML, the tricky part is mapping those to the target API's required array structure. Let's walk through concrete examples to make this clear.
First, let's assume you're using SimpleXML (a common PHP tool for XML parsing) to extract values. For example, if your source XML looks like this:
<sourceData> <customer> <customerId>789</customerId> <fullName>Jane Smith</fullName> <email>jane.smith@example.org</email> </customer> <purchase> <invoiceNumber>INV-2024-001</invoiceNumber> <amount>49.95</amount> <purchaseDate>2024-05-20</purchaseDate> </purchase> </sourceData>
Your extraction code might look like this (which you said you already have working):
// Fetch XML from source API (or load from string/file) $xmlResponse = file_get_contents('https://source-api.com/data'); $xml = simplexml_load_string($xmlResponse); // Extract the values you need $customerId = (string)$xml->customer->customerId; $fullName = (string)$xml->customer->fullName; $invoiceNum = (string)$xml->purchase->invoiceNumber; $purchaseAmount = (float)$xml->purchase->amount;
The key here is to exactly match the target API's required key names and nested structure. Let's say the target API expects a payload like this:
$targetPayload = [ 'client' => [ 'external_reference' => '', 'name' => '', 'contact_details' => [ 'email_address' => '' ] ], 'order' => [ 'invoice_id' => '', 'total' => '', 'transaction_date' => '' ] ];
You just need to assign your extracted values to the correct keys:
$targetPayload = [ 'client' => [ 'external_reference' => $customerId, 'name' => $fullName, 'contact_details' => [ 'email_address' => (string)$xml->customer->email // You can also use the extracted variable here ] ], 'order' => [ 'invoice_id' => $invoiceNum, 'total' => $purchaseAmount, 'transaction_date' => (string)$xml->purchase->purchaseDate ] ];
- Validate required fields: If the target API has mandatory fields, add checks to avoid sending empty values:
if (empty($customerId)) { throw new Exception("Critical error: Customer ID missing from source XML"); } - Verify the array structure: Print the final array to double-check it matches the target API's specs:
print_r($targetPayload); // Or use var_dump for more detailed type info var_dump($targetPayload); - Deal with repeated nodes: If your XML has multiple entries (e.g., multiple purchases), loop through them to build nested arrays:
$targetOrders = []; foreach ($xml->purchases->purchase as $purchase) { $targetOrders[] = [ 'invoice_id' => (string)$purchase->invoiceNumber, 'total' => (float)$purchase->amount ]; } $targetPayload['orders'] = $targetOrders;
Most APIs accept JSON, so convert your array to JSON and send it via cURL or Guzzle:
// Convert array to JSON $jsonPayload = json_encode($targetPayload); // Send via cURL $ch = curl_init('https://target-api.com/insert-data'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $apiResponse = curl_exec($ch); curl_close($ch); // Handle the response if ($apiResponse === false) { // Handle cURL error } else { $responseData = json_decode($apiResponse, true); // Process success/error from target API }
内容的提问来源于stack exchange,提问作者kat-trax

