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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

3 Comments

If we've got great minds (well, that would be good news, wouldn't it ? ), then, yes they do ;-)
I would of given you both a "tick" as both answers are equally right, but sadly I couldn't.
Boah, don't worry about that :-) What matters is that you got an (well, two ^^ ) answer(s).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.