【发布时间】:2020-08-14 14:12:33
【问题描述】:
我的以下代码有一些问题:
<?php
$url = "192.168.0.1:10040";
$xml = '<root><list><MatrixConnectionList><DviConsole type="name">Monitor X</DviConsole></MatrixConnectionList></list></root>';
$headers = array(
"Content-type: text/xml",
"Content-length: " . strlen($xml),
"Connection: close",
);
//Execute the curl init
$ch = curl_init();
//Add URL to Curl
curl_setopt($ch, CURLOPT_URL, $url);
//Return response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//set timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
//Add post option to curl
curl_setopt($ch, CURLOPT_POST, true);
//Add curel post field
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//Add headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Add verbose for error logging
curl_setopt($ch, CURLOPT_VERBOSE, true);
//Execute Curl
$data = curl_exec($ch);
//Print response
error_log(print_r($xml, TRUE));
error_log(print_r($data, TRUE));
//Log errors and close curl
if(curl_errno($ch))
print curl_error($ch);
else
curl_close($ch);
?>
回复应该是这样的:
<?xml version="1.0" encoding="utf-8"?><root><result type="list"><MatrixConnectionList><item><cpuId>0x0000</cpuId><cpuCl>DviCpu</cpuCl><cpuName>MISC</cpuName><cpuPoweredOn>true</cpuPoweredOn><signalType>viewonly</signalType><consoleId>0x000000</consoleId><consoleCl>DviConsole</consoleCl><consoleName>Monitor X</consoleName><connectionOwnerId>0x00000000</connectionOwnerId><connectionOwnerCl>DviMatrix</connectionOwnerCl><connectionOwnerPort>2</connectionOwnerPort><connectionOwnerName>Matrix X</connectionOwnerName><consoleConfigEnable>1</consoleConfigEnable><consolePoweredOn>true</consolePoweredOn><userName>0000000</userName><transmission>2</transmission></item></MatrixConnectionList></result></root>
除了我检查我的 Apache 错误日志时,我会看到以下内容:
* upload completely sent off: 118 out of 118 bytes
* Operation timed out after 5001 milliseconds with 1456 out of -1 bytes received
[Thu Apr 30 10:48:05.967278 2020] [php7:notice] [pid 20251] [client 192.168.0.2:6000] , referer: http://192.168.0.1/pages/test.php
我在这里遗漏了什么吗?为什么 curl_exec 不将返回的字符串分配给我的变量。
谢谢!
【问题讨论】:
-
“操作在 5001 毫秒后超时,收到 -1 个字节中的 1456 个” - 听起来您的远程端点没有正确响应请求? -1 可能表示它没有发送 Content-Length 标头,如果它也没有关闭连接,则 cURL 无法知道何时应该收到 all 数据.
-
@CBroe 谢谢!我还没有考虑过。似乎端点没有关闭它的响应,并且 $data 变量永远不会被填充。