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

2024-03-13

由于我是 PHP 新手,所以我很难使用 PHP。问题是我没有从curl 请求中获得任何返回值。我正在访问一个远程文件,其中包含以下代码:

测试.php:

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

我拨打电话的脚本。

请求值.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, TRUE);
  curl_setopt($ch, 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。就你而言,你没有回应任何内容。您调用一个返回数组的函数,但不打印该数组,因此不会将任何内容发送到输出。如果你想获得相同的数组requestVal.php在curl请求之后,您需要以某种方式对其进行编码,我建议使用JSON,因为它很容易开始。举个简单的例子,代替$test->getCall();你可以这样做:

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

And in requestVal.php:

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

您可以在以下位置找到每个功能的说明:php.net.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何获取数组值作为curl php请求的返回值? 的相关文章

随机推荐