PHP / CURL / JSON:将项目分配给var

时间:2017-08-01 19:19:09

标签: php json curl

我有这个100%工作的PHP代码并显示以下结果,但是如何将这些数据用作单个项目?

我过去经常使用以下内容:

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

但这并不适用于此。我希望能够分隔每个项目并为其分配一个var,以便我可以使用它制作广告。

PHP卷曲代码:

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

结果:

    {
 "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": ""
  }
 ]
}   

2 个答案:

答案 0 :(得分:1)

此结果是JSON。使用函数json_decode()将字符串解码为数组。你可以定期访问它的价值。

示例:

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

...其中$result代表您的未知结果字符串。

答案 1 :(得分:0)

您可以像这样使用循环个人数据:

<?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']
    }
  }
?>