PHP中PDF转XSD_BASE64BINARY适配SOAP服务的正确方法
Hey there! No worries about your English at all—let's get this sorted step by step.
First, let's clarify what XSD_BASE64BINARY is: it's a data type defined in XML Schema (XSD) specifically for transmitting binary data over SOAP (which uses XML under the hood). Since XML can't handle raw binary bytes directly, this type just means "binary data encoded as a Base64 string"—that's all it is! The Java "Binary Array" people mentioned is just the raw byte data of the file, which is the starting point for both Java and PHP.
Your initial guess was almost right—here's the exact, working flow for PHP:
Step 1: Read the PDF's raw binary content
You need to grab the actual bytes of the PDF file without any modifications. In PHP, file_get_contents() is perfect for this because it's binary-safe (it reads the file exactly as it is, no character encoding changes).
Step 2: Encode the binary data to Base64
Use PHP's built-in base64_encode() function on the raw binary content. This converts the bytes into a plain text string that fits the XSD_BASE64BINARY requirement.
Step 3: Pass the encoded string to your SOAP request
Feed this Base64 string into the corresponding parameter of your SOAP method (make sure the parameter name matches what the WebService expects in its WSDL).
Full Working Code Example
// Replace with your actual PDF file path $pdfPath = '/home/user/documents/my_file.pdf'; // Step 1: Read raw binary data $pdfBinary = file_get_contents($pdfPath); // Check if the file was read successfully if ($pdfBinary === false) { throw new Exception("Couldn't read PDF file—check the path and file permissions!"); } // Step 2: Encode to Base64 (this is your XSD_BASE64BINARY value) $xsdBase64Data = base64_encode($pdfBinary); // Step 3: Send via SOAP Client (adjust to match your WebService's WSDL and method) try { $soapClient = new SoapClient('https://your-webservice-url.com/wsdl'); $result = $soapClient->submitPdf([ 'pdfDocument' => $xsdBase64Data // Match the parameter name from the WSDL ]); echo "SOAP request sent successfully!"; } catch (SoapFault $e) { echo "SOAP Error: " . $e->getMessage(); }
Why Your First Attempt Might Have Failed
- Incorrect file path: Double-check that the path to your PDF is absolute and that PHP has permission to read the file.
- Accidental text encoding: If you used functions like
fopen()in text mode instead of binary mode, it might have altered the binary data (butfile_get_contents()avoids this). - Wrong parameter name: Make sure the parameter you're passing the Base64 string to matches exactly what the WebService defines in its WSDL (case-sensitive!).
Quick Note on Java's "Binary Array"
Java uses byte arrays to hold raw binary data, which is exactly what file_get_contents() returns in PHP (as a string of bytes). Both languages then encode that raw data to Base64 to get the XSD_BASE64BINARY format—same logic, just different syntax.
内容的提问来源于stack exchange,提问作者carlosalvet

