【问题标题】:Get api result from URL using PHP使用 PHP 从 URL 获取 api 结果
【发布时间】:2017-05-08 11:01:53
【问题描述】:

以下 URL 来自 FobBugz API 文档: https://kakapo.fogbugz.com/api.asp?cmd=search&q=project:inbox%20assignedTo:Elinor&cols=ixProject,ixPersonAssignedTo,sTitle&max=2&token=04t9123822q4kbba09nt740inhibk2 (you can find it here)

如果我将上述 URL 复制并粘贴到 Web 浏览器中,我会收到 XML 响应。我想做的是创建一个函数,该函数将 XML 响应作为其结果返回。

我被卡住了,它根本不起作用。我似乎得到的只是一个空字符串。当我在 FogBugz 网站上使用这个“示例”时,我得到 XML 告诉我我没有登录。

下面的函数主要来自这里:Make a HTTPS request through PHP and get response 我已经搞砸了几个小时没有成功。

function searchBug(){

$data =  "https://kakapo.fogbugz.com/api.asp?cmd=search&q=project:inbox%20assignedTo:Elinor&cols=ixProject,ixPersonAssignedTo,sTitle&max=2&token=04t9123822q4kbba09nt740inhibk2"; 
    //echo $data;
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, False);
    $result = curl_exec($ch);
    curl_close($ch);
    echo $result;
}

[编辑:回应评论] 我想收到的回复是:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<response>
<error code="3">
<![CDATA[ Not logged in ]]>
</error>
</response>

当我粘贴 URL 并按 Enter 键时,我的浏览器中会显示该内容。

【问题讨论】:

  • 你想收到什么?
  • 好吧,错误已经显示,你只是没有登录,你可能需要先创建一个logincall
  • 我试过了,对我有用
  • @mrweinh - 作为对您删除的答案的回应,我有一个帐户和 API 令牌,但由于我从示例中得到了结果,我认为 PHP 脚本应该返回相同的结果。
  • @SlowLearner 是的,如果你想在浏览器中看到你的 xml 响应,不要忘记发送 xml 标头

标签: php curl libcurl


【解决方案1】:

你可以这样做:-

<?php
function searchBug($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = searchBug('https://kakapo.fogbugz.com/api.asp?cmd=search&q=project:inbox%20assignedTo:Elinor&cols=ixProject,ixPersonAssignedTo,sTitle&max=2&token=04t9123822q4kbba09nt740inhibk2');
header('Content-Type: text/xml');
echo $sXML;

输出:- http://prntscr.com/f5fj44

【讨论】:

  • 好的 - 基于此,我进一步了解,足以从文档中删除 HTML 标头....谢谢
  • @SlowLearner 很高兴为您提供帮助:):):)
猜你喜欢
  • 2015-11-11
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
相关资源
最近更新 更多