Get usable array from a curl response, which is formatted as a php array
Solution 1
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.
Solution 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
- i.e. and array, serialized with
- And, on your side, unserialize the data, to get the array back,
- with either
unserialize
- or
json_decode
- with either
Mint
I use a Mac at home, a remote Debian server. I Dual boot Win 7 for the occasional game. I also run VMs of several other Operating Systems (Debian, Ubuntu, CentOS, Win 7, Win XP). I'm learning HTML, CSS, PHP, MYSQL, Javascript, BASH Scripting. I have little experience with C#, Perl, Python. I want to learn Python and C (or C++) one day.
Updated on June 09, 2022Comments
-
Mint almost 2 years
$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?
-
Mint about 14 yearsOk, yeah I change the page I'm querying :) Thanks.
-
Pascal MARTIN about 14 yearsIf we've got great minds (well, that would be good news, wouldn't it ? ), then, yes they do ;-)
-
Mint about 14 yearsI would of given you both a "tick" as both answers are equally right, but sadly I couldn't.
-
Pascal MARTIN about 14 yearsBoah, don't worry about that :-) What matters is that you got an (well, two ^^ ) answer(s).