当我使用curl,通过php发出HTTP GET请求时,我得到了这个回复:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<apiStatus>ok</apiStatus>
<matches>1</matches>
<unit type="campaign">
<id>42</id>
<name>think_deep</name>
</unit>
<units>1</units>
</root>
当我尝试获取此输出时,为了创建一个SimpleXMLElement,我得到了这个错误:
PHP Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : Start tag expected, '<' not found in /home/simone/Development/dotadv/cxense/scripts/SearchForCampaign.php on line 35
PHP Warning: SimpleXMLElement::__construct(): 1 in /home/simone/Development/dotadv/cxense/scripts/SearchForCampaign.php on line 35
PHP Warning: SimpleXMLElement::__construct(): ^ in /home/simone/Development/dotadv/cxense/scripts/SearchForCampaign.php on line 35
PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/simone/Development/dotadv/cxense/scripts/SearchForCampaign.php:35
Stack trace:
#0 /home/simone/Development/dotadv/cxense/scripts/SearchForCampaign.php(35): SimpleXMLElement->__construct('1')
#1 {main} thrown in /home/simone/Development/dotadv/cxense/scripts/SearchForCampaign.php on line 35
使用var_dump()我发现输出是:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<apiStatus>ok</apiStatus>
<matches>1</matches>
<unit type="campaign">
<id>42</id>
<name>think_deep</name>
</unit>
<units>1</units>
</root>
bool(true)
bool(true)
那么,......这是什么问题?
$curl = curl_init();
$url = 'http://stage.emediate.eu' . $request->uri();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
]);
$resp = curl_exec($curl);
var_dump($resp, true);
答案 0 :(得分:1)
因为您没有设置选项CURLOPT_RETURNTRANSFER
,所以curl_exec会因请求而返回true或false。因此,$ resp变为true,我们可以在var_dump($resp, true);
bool(true)
bool(true)
要接收xml,请将代码更改为
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1
]);