PHP处理SOAP返回含CDATA的XML转JSON遇阻求助
Hey there! Let’s work through this XML parsing problem together—SOAP responses can be tricky sometimes, but we’ll get it sorted. Here are the most common fixes to try when simplexml_load_string returns empty despite having a valid-length string:
1. Clean up hidden characters or encoding mismatches
SOAP responses often come with extra whitespace, a hidden byte order mark (BOM), or unexpected encoding that throws off simplexml. Try cleaning your string first:
// Remove any leading BOM (common in UTF-16/32 responses) $return = preg_replace('/^\x{FEFF}/u', '', $return); // Trim extra whitespace from start/end $return = trim($return); // Check and convert to UTF-8 if needed $currentEncoding = mb_detect_encoding($return); if ($currentEncoding !== 'UTF-8') { $return = mb_convert_encoding($return, 'UTF-8', $currentEncoding); }
Then re-run simplexml_load_string on the cleaned string.
2. Enable XML error reporting to see what’s breaking
Simplexml fails silently by default—turn on error reporting to get concrete details about why parsing is failing:
libxml_use_internal_errors(true); $xml = simplexml_load_string($return); if (!$xml) { echo "XML Parsing Errors:\n"; foreach(libxml_get_errors() as $error) { echo "- ", $error->message, " (Line ", $error->line, ")\n"; } libxml_clear_errors(); }
This will tell you if there’s invalid syntax, missing tags, or namespace issues you’re missing.
3. Extract the actual data from the SOAP envelope
The raw __getLastResponse() usually includes the full SOAP envelope (with <soap:Envelope> and <soap:Body> tags) instead of just your target XML. You’ll need to extract the inner content first:
// Load the full SOAP response $soapEnvelope = simplexml_load_string($return); // Register the SOAP namespace (check your response's xmlns:soap value to match) $soapEnvelope->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/'); // Grab the first element inside the SOAP Body $responseData = $soapEnvelope->xpath('//soap:Body/*')[0]; // Convert the extracted data back to a clean XML string $cleanXml = $responseData->asXML(); // Now parse this clean XML $xml = simplexml_load_string($cleanXml);
Double-check the namespace URI in the registerXPathNamespace call—your SOAP response might use a different one (like a custom namespace for your service).
4. Convert valid XML to JSON
Once you have a working SimpleXMLElement, converting to JSON is straightforward:
// Convert XML to JSON string $json = json_encode($xml); // Or convert directly to an associative array for easier processing $dataArray = json_decode($json, true);
Note that complex XML structures (like repeated elements or nested namespaces) might need extra handling to convert cleanly to JSON—adjust based on your specific schema.
内容的提问来源于stack exchange,提问作者Alexandre Bento

