dongsuo0517 2012-06-11 06:24
浏览 12
已采纳

php cURL发布到外部域并使用响应

Ok this may be a simple question. I have a working concept of posting to the external domain and getting it to work with the post to do what i want and need it to do. However. I need it to after doing what I want it to do output a JSON response that I can in turn work with the domain of origin. I know with cURL I should be able to grab whats output but Im not sure how to work it into what I have, as this was initially given to me by someone else to work with and I am not extremely familiar with cURL

this is what I have thus far that works to post to the domain.

$url = 'http://thedomain.com/new/';
        $fields = array(
                    'api'=>'randomkey',
                    'id'=>'100000',
                    'url'=>urlencode($longurl),
                );

    //url-ify the data for the POST
    $fields_string = '?';
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string,'&');

    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

    //execute post
    $result = curl_exec($ch);

    //close connection
    curl_close($ch);

how can I alter this to take what the external site would spit out in JSON form and have it so I can work with it from the domain I am working with?

  • 写回答

1条回答 默认 最新

  • dptrmt4366 2012-06-11 06:38
    关注

    You are missing the RETURNTRANSFER option which tells cURL to return the response to your $result:

    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    

    Now that you have the response you can manipulate it and json_encode() then output it as needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加