Get a useful array from a curl response that 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 that PHP can see that it is an array and treat it as such, but when I do something like

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

he gives an error:

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

(line 75 is an echo just above)

What am I doing wrong?

+3
source share
2 answers

The data you receive is probably not an array, but a string containing the structure of the array, for example. displayed on print_r(). This data type will not be automatically converted back to a PHP array.

, , , serialize() json_encode() , curl, (unserialize() json_decode()) . PHP.

URL-, , (yuck!), eval() - , , .

+4

$outputArray , , , - print_r().

, PHP , - , ; .


:

  • script, , ,
    • . , serialize
    • json_encode
  • , , , ,
    • unserialize
    • json_decode
+2

Source: https://habr.com/ru/post/1739757/


All Articles