首页 > 解决方案 > 通过 PHP curl 发送 XML 后提取 XML 响应的问题

问题描述

我的以下代码有一些问题:

<?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 不将返回的字符串分配给我的变量。

谢谢!

标签: phpxmlcurl

解决方案


您正在访问的服务器没有发送Content-Length标头(根本不发送标头,或者发送格式错误的标头,我不确定,您可以查看详细日志以找出答案),这使得 curl 继续阅读直到远程服务器关闭套接字,服务器使用超过 5 秒的时间关闭套接字,5 秒似乎是您的默认 CURLOPT_TIMEOUT,因此您收到超时错误.. 当您收到 CURLOPT_RETURNTRANSFER 错误时,curl_exec()不返回响应字符串,而是返回 bool(false) 以指示发生了错误。

您可以尝试增加 CURLOPT_TIMEOUT 以查看服务器是否最终会关闭套接字,

// timeout at 10 seconds instead of 5, server reponds slowly sometimes..
curl_setopt($ch,CURLOPT_TIMEOUT,10);

或者你可以删除

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

并添加

$response="";
curl_setopt($ch,CURLOPT_WRITEFUNCTION,function($ch,string $data)use(&$response):int{
    $response.=$data;
    return strlen($data);
});
$error_if_false=curl_exec($ch);
if(false===$error_if_false){
     // error, but your response is now in $response regardless.
}

推荐阅读