PHP接收外部网站POST XML数据遇阻,求解决方案及验证方法
Hey there! Let's fix your XML receiving issue step by step—first, I notice a key misunderstanding in the code you tried, so let's clear that up first.
The Core Issue with Your Current Code
The functions simplexml_load_file("https://example.com") and DOMDocument::load('https://example.com') are designed to pull XML data from an external URL (like fetching a file from someone else's server). But your goal is to receive XML data that's sent to your own URL (via a POST request from another website). These are totally different use cases, so those methods won't work here.
Step 1: Correctly Receive XML Data Sent to Your URL
When another site sends XML to your URL, it's almost always via a POST request with the XML in the request body. In PHP, you can capture this raw data using php://input. Here's how to handle it with both SimpleXML and DOMDocument:
Using SimpleXML
// Capture the raw XML from the request body $rawXml = file_get_contents('php://input'); // First, check if we actually received data if (empty($rawXml)) { echo "No XML data was received."; exit; } // Parse the raw XML string libxml_use_internal_errors(true); // Suppress default error output $xml = simplexml_load_string($rawXml); if ($xml === false) { echo "Failed to parse XML. Errors:\n"; foreach(libxml_get_errors() as $error) { echo "- " . $error->message . "\n"; } } else { // Success! Now you can work with the XML data echo "Parsed XML successfully:\n"; print_r($xml); // Example: Access a specific element // echo "Value of 'some_element': " . $xml->some_element; }
Using DOMDocument
$rawXml = file_get_contents('php://input'); if (empty($rawXml)) { echo "No XML data received."; exit; } $dom = new DOMDocument(); libxml_use_internal_errors(true); if ($dom->loadXML($rawXml)) { // Parsing succeeded echo "Root element: " . $dom->documentElement->tagName . "\n"; // Example: Find a specific node // $nodes = $dom->getElementsByTagName('data'); // foreach ($nodes as $node) { // echo "Data value: " . $node->nodeValue . "\n"; // } } else { echo "DOM parsing errors:\n"; foreach(libxml_get_errors() as $error) { echo "- " . $error->message . "\n"; } }
Step 2: Verify if Data is Actually Reaching Your URL
To confirm whether the external site is sending data correctly, try these methods:
1. Log All Requests
Write the full request details (headers, body, timestamp) to a log file. This lets you check exactly what's being sent to your URL:
$logEntry = [ 'timestamp' => date('Y-m-d H:i:s'), 'request_method' => $_SERVER['REQUEST_METHOD'], 'request_headers' => getallheaders(), 'raw_body' => $rawXml ]; // Append to a log file (make sure the file is writable by PHP) file_put_contents('xml_request_logs.txt', print_r($logEntry, true) . "\n---\n", FILE_APPEND);
2. Send a Confirmation Response
After receiving data, send a simple response back to the sender. This lets them (and you) verify delivery:
header('Content-Type: text/plain'); echo "XML received successfully. Data length: " . strlen($rawXml); exit;
3. Test with a Tool
Simulate a request to your URL using tools like Postman or curl to make sure your code works before relying on the external site. Here's a curl command example:
curl -X POST -H "Content-Type: application/xml" -d '<root><user><name>Test</name><email>test@example.com</email></user></root>' https://your-url-here.com
Common Troubleshooting Tips
- Check Request Method: Ensure the external site is using POST (XML is almost never sent via GET). If they're using GET, you'll need to check
$_GETinstead (but this is unusual for XML). - Validate Content-Type: The sender should set the
Content-Typeheader toapplication/xmlortext/xml. If not, some servers/ frameworks might discard the request body. - Check PHP Configurations: Make sure
php://inputisn't blocked byopen_basedirrestrictions (this is rare, but worth checking if you're on a shared host). - Validate XML Syntax: If parsing fails, use
libxml_get_errors()to see exactly what's wrong—sometimes the sender's XML has typos or missing closing tags.
内容的提问来源于stack exchange,提问作者sushan shrestha

