【问题标题】:PHP cURL can't create XMLPHP cURL 无法创建 XML
【发布时间】:2016-05-23 16:15:28
【问题描述】:

我正在尝试从 URL 获取 XML 文件。 但我只从文件中获取文本,没有语法。

我的代码:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://services.mobile.de/search-api/search?country=DE&sort.field=makeModel&sort.order=ASCENDING');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic '. base64_encode("username:password"), 'Accept: 
    application/xml'));
    $xml = new SimpleXMLElement(curl_exec($ch));//line 14
    curl_close($ch);
    print_r($xml);

我的输出:

....sensorsBlackEuro5PetrolManual gearboxAutomatic air conditioningUsed vehicle150.90525114.812090CarSmall CarVolkswagenPoloCentral lockingElectric windowsImmobilizerPower Assisted SteeringABSESPFull Service HistoryElectric side mirrorOn-board computerCD playerTuner/radioIsofix (child seat anchor points)Parking sensor

Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : Start tag expected, '<' not found in /Applications/XAMPP/xamppfiles/htdocs/test.php on line 14

Warning: SimpleXMLElement::__construct(): 1 in /Applications/XAMPP/xamppfiles/htdocs/test.php on line 14

Warning: SimpleXMLElement::__construct(): ^ in /Applications/XAMPP/xamppfiles/htdocs/test.php on line 14

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /Applications/XAMPP/xamppfiles/htdocs/test.php:14 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/test.php(14): SimpleXMLElement->__construct('1') #1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/test.php on line 14

更新:

我现在在浏览器中得到了正确的字符串:

echo '<pre>';
echo htmlspecialchars(print_r(curl_exec($ch), true));
echo '</pre>';

但是当我尝试使用时:

$sxe = simplexml_load_string($re);
print_r($sxe);

我只知道这个:

SimpleXMLElement Object ( )

【问题讨论】:

  • 当你在浏览器上打开xml url时,你能看到有效的xml吗?
  • 您知道 API 返回 XML 的事实吗?如果使用 curl 从命令行发送请求会发生什么?
  • 您确定要从您的请求中获取 XML 文件吗? $response = curl_exec($ch); echo htmlspecialchars($response); 向您展示了什么?
  • @hakkikonu 我通过浏览器获得了正确的 XML。
  • @JimGarrison 我想是的。 services.mobile.de/manual/search-api.html

标签: php xml curl


【解决方案1】:

new SimpleXMLElement() 只有一个参数需要 XML (manual),curl_exec($ch) 默认返回 truefalse (manual)。因此很清楚为什么这不起作用:

$xml = new SimpleXMLElement(curl_exec($ch));//line 14

您可能希望按照 curl_exec 手册页中的提示进行操作:

成功时返回 TRUE,失败时返回 FALSE。但是,如果 设置了 CURLOPT_RETURNTRANSFER 选项,它将返回结果 成功,失败则为 FALSE。

...但您仍然需要验证它不是false。如果您忽略错误检查,您的代码将不时随机失败。

【讨论】:

  • with curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);我只得到 SimpleXMLElement 对象()
  • 在知道它是否好之前,不要通过几层代码来处理响应。从例如开始var_dump().
  • 问题是 curl 只返回原始 xml 文件中的一个列表。缺少 XML 语法。
  • 您是否偶然在 HTML 文档中显示了 XML 标记,然后通过浏览器看到它们全部呈现?如果是这样,您必须使用“查看源代码”菜单项。
  • 太好了,谢谢! xml 被浏览器隐藏。我可以通过 echo htmlspecialchars(curl_exec($ch)); 看到它但是 $xml = $xml = simplexml_load_string(curl_exec($ch)) 或 die("ERROR"); print_r($xml) 仍返回“错误”(应为开始标记,未找到“
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
相关资源
最近更新 更多