如何使用file_get_contents和expedia XML API修复411 Length Required错误?

use*_*625 1 php xml api http

我正在使用xml api(php)项目进行在线酒店预订.当我在预订代码中工作时,它显示以下错误

"Warning: file_get_contents(https://...@gmail.com</email><firstName>test</firstName><lastName>smith</lastName><homePhone>8870606867</homePhone><creditCardType>CA</creditCardType><creditCardNumber>5401999999999999</creditCardNumber>....</HotelRoomReservationRequest>) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 411 Length Required"

它是我的代码

$context  = stream_context_create(
                array(
                    'http' => array(
                        'method' => 'POST',
                        'header' => "Content-type: application/x-www-form-urlencoded",
                        "Accept: application/xml"
                    )
                )
            );
$url ='https://book.api.ean.com/....';
$xml = file_get_contents($url, false, $context);
Run Code Online (Sandbox Code Playgroud)

这是发送信用信息plz请给我建议什么类型的错误....

hak*_*kre 6

根据RFC2616 10.4.12:

10.4.12 411 Length Required

   The server refuses to accept the request without a defined Content-
   Length. The client MAY repeat the request if it adds a valid
   Content-Length header field containing the length of the message-body
   in the request message.
Run Code Online (Sandbox Code Playgroud)

您需要将Content-Length标头添加到您的POST请求中.这是POST请求正文的大小(以字节为单位).获取strlenPOST主体可以使用的长度.由于您的代码示例未显示任何POST正文,因此很难给出具体示例.邮件正文与['http']['content']流上下文中的条目一起传递.

也许,如果你设置它已经足够content入门(见HTTP上下文选项文件).

编辑:以下示例代码可能会解决您的问题.它演示了如何使用file_get_contents和设置包含Content-Length标头的标头通过POST请求将一些XML发送到服务器.

$url = 'https://api.example.com/action';
$requestXML = '<xml><!-- ... the xml you want to post to the server... --></xml>';
$requestHeaders = array(
    'Content-type: application/x-www-form-urlencoded',
    'Accept: application/xml',
    sprintf('Content-Length: %d', strlen($requestXML));
);

$context = stream_context_create(
                array(
                    'http' => array(
                        'method'  => 'POST',
                        'header'  => implode("\r\n", $requestHeaders),
                        'content' => $requestXML,
                    )
                )
            );
$responseXML = file_get_contents($url, false, $context);

if (FALSE === $responseXML)
{
    throw new RuntimeException('HTTP request failed.');
}
Run Code Online (Sandbox Code Playgroud)

如果您需要更好的误差控制,请参阅ignore_errorsHTTP上下文选项文件$http_response_header文档.我的博客文章中提供了HTTP响应头的详细处理:HEAD首先使用PHP Streams.