Reputation: 353
I am having hard time using curl PHP as I am new to PHP. The problem is that I am not getting any return value from a curl request. There is a remote file I am accessing which has this code:
$test->getCall();
public function getCall() {
$var = array('fname'=>'jack','lname'=>'williams');
return $var;
}
The script from which I am making the call.
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);
}
I don't get any value in $p_result
nor an exception curl_error()
.
Upvotes: 4
Views: 28814
Reputation: 99
like Ranty said, you can return a string at test.php code
$test->getCall();
public function getCall() {
$var = array('fname'=>'jack','lname'=>'williams');
echo serialize($var);
}
So, you can caught a serialization data at requestVal.php code, by unserialize data from remote server
unserialize($content)
Upvotes: 0
Reputation: 3362
No matter what you echo in your test.php
, curl will read it as a String
. In your case, you echo nothing. You call a function that returns the array, but you don't print the array, so nothing is sent to output. If you want to get the same array in requestVal.php
after curl request, you need to encode it in some way, I would suggest JSON as it's easy to start with. For a quick example, in place of $test->getCall();
you could do:
echo json_encode($test->getCall());
And in requestVal.php
:
$array = json_decode(trim($p_result), TRUE);
print_r($array);
You can find each function description at php.net
.
Upvotes: 15
Reputation: 11364
If you are using curl you should expect exactly the same result as you'll get if you run your test.php script in any browser. So, if your test.php is like:
echo "123";
in your browser you'll see "123" and that's also you'll get inside your $p_result
variable. If your test.php is like:
function foo() {
return "123";
}
foo();
You see nothing in browser and get nothing in your $p_result
as well.
So, try change your test.php in something like that:
public function getCall() {
$var = array('fname'=>'jack','lname'=>'williams');
return $var;
}
var_dump($test->getCall()); // of course you will show these values in better way (depends on your needs)
Upvotes: 1