0

I've tried to print GET request data using CURL in php. But i can't understand why my code is not working. It will show syntax error, unexpected 'echo' (T_ECHO) Given bellow my code :

<?php

# An HTTP GET request example

   $url = 'https://jsonstorage.net/api/items/b82e19e3-aec2-4415-a0a7- 
   28f4fff8270a';
   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_TIMEOUT, 5);
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

   $data = curl_exec($ch);

   curl_close($ch);
   $someArray = json_decode($data, true);

   if ( $someArray ) {
    echo $someArray[0]->type;

   }

  else {
     echo "bad data";
  }

 curl_close($ch);


?>

I tried this by following this post: How to parse json response from CURL from-curl. Please give me hints how can i achieve my goal. Thanks.

Update

The curl call returns data which results in the following array being assigned to $someArray:


array (size=2)
  'data' => 
    array (size=1)
      0 => 
        array (size=4)
          'type' => string 'articles' (length=8)
          'id' => string '1' (length=1)
          'attributes' => 
            array (size=4)
              ...
          'relationships' => 
            array (size=1)
              ...
  'included' => 
    array (size=1)
      0 => 
        array (size=3)
          'type' => string 'people' (length=6)
          'id' => string '42' (length=2)
          'attributes' => 
            array (size=3)
              ...
ficuscr
  • 6,975
  • 2
  • 32
  • 52
offline
  • 69
  • 1
  • 11
  • Remember `var_dump` is your friend. Try `echo $someArray['data'][0]['type'];`. Missing an index, also `Array`, not `Object`, so no `->`. Probably want to use `isset` before trying to echo things that aren't there. – ficuscr Sep 04 '19 at 19:47
  • Possible duplicate of [PHP parse/syntax errors; and how to solve them?](https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them) – ficuscr Sep 04 '19 at 19:49
  • @hanshenrik agreed. I get `Undefined offset: 0` on that first echo line. I still stand by my first comment. – ficuscr Sep 04 '19 at 20:52
  • Sure, but there are two notices prior to that (*E_ALL*). OP's main issue is confusion over the array indexes - also fits with what he is asking. I added the array the cURL call results in to the question. – ficuscr Sep 04 '19 at 21:50

0 Answers0