0

I have this PHP code that works 100% and it displays the below results, however how can I use this data as individual items?

I'm used to using things like :

$title = $data['selection3']['name']; 
echo $title

But that doesn't work here. I'd like to be able to seperate each item and assign it a var so that I can build an ad with it.

PHP Curl code:

<?php
    function origin($projecttoken,$apikey,$format) {
        $ch = curl_init();
        $apiuri = 'https://www.parsehub.com/api/v2/projects/'.$projecttoken.'/last_ready_run/data?api_key='.$apikey.'&format='.$format.'';
        curl_setopt($ch, CURLOPT_URL, $apiuri);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch,CURLOPT_ENCODING, '');
            if(curl_exec($ch) === false){
                echo curl_error($ch) . '<br />';
            }
        $data = curl_exec($ch);
        curl_close($ch);
        return($data);
    }
?>

    <pre>
    <?php
    print_r(origin('xxxxxx','xxxxxx','json'));
    ?>
    </pre>

The Results:

    {
 "selection3": [
  {
   "name": "Medal of Honor™ Pacific Assault",
   "url": "https://www.origin.com/usa/en-us/store/medal-of-honor/medal-of-honor-pacific-assault/standard-edition"
  },
  {
   "name": "Join the Fight for Freedom"
  },
  {
   "name": "This World War II shooter is On the House and yours to own totally free."
  },
  {
   "name": "FREE"
  },
  {
   "name": "Get It Now",
   "url": ""
  }
 ],
 "selection6": [
  {
   "name": "Battlefield 4™ Dragon's Teeth",
   "url": "https://www.origin.com/usa/en-us/store/battlefield/battlefield-4/expansion/battlefield-4-dragons-teeth"
  },
  {
   "name": "Upgrade Your Fight"
  },
  {
   "name": "Add this expansion to your library for free and dominate the battlefield. It's On the House! (Requires base game to play.)"
  },
  {
   "name": "FREE"
  },
  {
   "name": "Get It Now",
   "url": ""
  }
 ]
}   
Canuto-C
  • 391
  • 2
  • 7
  • 17
Jay Hill
  • 13
  • 3

2 Answers2

1

This result is in JSON. Use the function json_decode() to decode the string into an array. THen you can access it's values regularly.

Example:

$data = json_decode($result, true);
echo $data["selection3"]["name"];

... where $result represents your unknown result string.

instead
  • 3,101
  • 2
  • 26
  • 35
Dan
  • 5,140
  • 2
  • 15
  • 30
0

You use looping individual data like this:

<?php
  $data = origin('xxxxxx','xxxxxx','json');
  $dataArray = json_decode($data, true);
  if(!empty($dataArray){
    foreach($dataArray as $key => $val){
      $item = $dataArray[$key];
      echo "<pre>". json_decode($item);
      //$item['name'], $item['url']
    }
  }
?>
Chandra Kumar
  • 4,127
  • 1
  • 17
  • 25