Mint
Mint

Reputation: 15897

Get usable array from a curl response, which is formatted as a php array

$ch = curl_init("url");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "test"); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$outputArray = curl_exec($ch);

Then $outputArray will contain:

Array
(
[0] => Array
    (
        [r1] => test response
        [r2] => 4
        [r3] => 32
    )

)

So I would think PHP can see that it's an array and treat it as such, but when I do something like

echo $outputCode[0][r_title]."\n";

it gives an error:

PHP Fatal error:  Cannot use string offset as an array in /www/test.php on line 75 

(line 75 being the echo one just above)

What am I doing wrong?

Upvotes: 3

Views: 11975

Answers (2)

Pekka
Pekka

Reputation: 449395

The data you are getting is probably not an array, but a string containing an array structure, e.g. output by print_r(). This kind of data will not automatically be converted back into a PHP array.

If you can control the page you are querying this from, encode the data using a method like serialize() or json_encode() and on the querying side, decode the data you get from curl using (unserialize() or json_decode()) respectively. Those functions will give you a proper PHP array.

If you have no way to change the way the URL outputs its data, the only way I can see is (yuck!) using eval() - I can elaborate on that if need be, but it's a really really bad idea.

Upvotes: 4

Pascal MARTIN
Pascal MARTIN

Reputation: 400952

Your $outputArray is a string, that seems to contain something like the ouput of print_r().

There is no way PHP can guess that string represents an array -- and it's not really close to the syntax that's used to declare an array ; so this will not work.


A solution would be :

  • to modify the remote script you're calling, so it returns a string containing some serialized data
    • i.e. and array, serialized with serialize
    • or with json_encode
  • And, on your side, unserialize the data, to get the array back,
    • with either unserialize
    • or json_decode

Upvotes: 2

Related Questions