API Youtube V3 JSON - PHP

0

I want to get dynamically with the title of the post, the "videoId" of youtube on my page to show the automatic videos:   link

<?
    $nombreproducto = $product->name;
    $googleApiUrl = "https://www.googleapis.com/youtube/v3/search?part=id&q=$nombreproducto&maxResults=1&key=AIzaSyBMdBIAc5VmMNV6M7aCwsKmQH8Yf4ctHmc";
    $ch = curl_init();

        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $googleApiUrl);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);

        curl_close($ch);
        $data = json_decode($response);
        $value = json_decode(json_encode($data), true);
      $output6 = get_object_vars($output6);
    $videoId = $value['items'][0]['id']['videoId'];

     echo "Id: $videoId<br>";
    ?>
<br><br>
<h2><? echo "Vídeo de $nombreproducto"; ?> en Youtube</h2>
<iframe class="videoproduct" width="560" height="315" src="https://www.youtube.com/embed/<? echo "$videoId";?>" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Here is the json, and the variable that I can not get:

    
asked by Ito Martinez Alonso 03.01.2019 в 13:22
source

1 answer

1

I found the solution. Instead of:

$videoId = $value['items'][0]['id']['videoId']; 

I had to put:

$videoId = $output6['items'][0]['id']['videoId']

This is the code with the modifications:

$nombreproducto0 = $product->name;
$nombreproducto = str_replace(" ", "+", $nombreproducto0);
$googleApiUrl = "https://www.googleapis.com/youtube/v3/search?part=id&q=$nombreproducto&maxResults=1&relevanceLanguage=es&key=AIzaSyBMdBIAc5VmMNV6M7aCwsKmQH8Yf4ctHmc";

 $c6 = curl_init();
  curl_setopt($c6, CURLOPT_URL, $googleApiUrl);
  curl_setopt($c6,  CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($c6, CURLOPT_HTTPHEADER, array(
  "Accept: application/json"
));
  $output6 = curl_exec($c6);
  curl_close($c6);
  $output6 = json_decode($output6,true);
  //$output6 = get_object_vars($output6);
 //print_r($output6);
$videoId = $output6['items'][0]['id']['videoId'];
    
answered by 03.01.2019 / 17:50
source