加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

如何在curl php请求中获取数组值作为返回值?

发布时间:2020-12-14 01:35:15 所属栏目:Linux 来源:网络整理
导读:我很难使用curl PHP,因为我是 PHP新手.问题是我没有从curl请求中获得任何返回值.我正在访问的远程文件具有以下代码: test.php的: $test-getCall();public function getCall() { $var = array('fname'='jack','lname'='williams'); return $var;} 我正在拨
我很难使用curl PHP,因为我是 PHP新手.问题是我没有从curl请求中获得任何返回值.我正在访问的远程文件具有以下代码:

test.php的:

$test->getCall();
public function getCall() {
  $var = array('fname'=>'jack','lname'=>'williams');
  return $var;
}

我正在拨打电话的脚本.

requestVal.php

try{
  $ch = curl_init();
  if (FALSE === $ch){
    throw new Exception('failed to initialize');
  }
  curl_setopt($ch,CURLOPT_URL,"http://www.xyz.com/app/src/test.php");
  curl_setopt($ch,CURLOPT_POST,TRUE);
  curl_setopt($ch,CURLOPT_POSTFIELDS,$msg);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,CURLOPT_FOLLOWLOCATION,1);
  $p_result = curl_exec($ch);
  var_dump($p_result);
  print_r($p_result);
  if (FALSE === $p_result) {
    throw new Exception(curl_error(),curl_errno());
    curl_close($ch);
  } else{
    curl_close($ch);
    return $p_result;
  }
}catch(Exception $e) {
  trigger_error(sprintf('Curl failed with error #%d: %s',$e->getCode(),$e->getMessage()),E_USER_ERROR);
}

我在$p_result中没有任何值,也没有curl_error()异常.

解决方法

无论你在test.php中回应什么,curl都会把它读成一个String.在你的情况下,你没有回音.您调用一个返回数组的函数,但是您不打印该数组,因此不会向输出发送任何内容.如果你想在curl请求之后在requestVal.php中获得相同的数组,你需要以某种方式对它进行编码,我建议使用JSON,因为它很容易入手.快速举例,代替$test-> getCall();你可以这样做:

echo json_encode($test->getCall());

在requestVal.php中:

$array = json_decode(trim($p_result),TRUE);
print_r($array);

您可以在php.net上找到每个功能描述.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读