views:

169

answers:

2
$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?

+1  A: 

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
Pascal MARTIN
Great minds think alike.... :)
Pekka
If we've got great minds *(well, that would be good news, wouldn't it ? )*, then, yes they do ;-)
Pascal MARTIN
I would of given you both a "tick" as both answers are equally right, but sadly I couldn't.
Mint
Boah, don't worry about that :-) What matters is that you got an (well, two ^^ ) answer(s).
Pascal MARTIN
+1  A: 

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.

Pekka
Ok, yeah I change the page I'm querying :)Thanks.
Mint