0

I am sending a request to youtube API to get a playlist:

      // make GET request to the YouTube API
      $response = wp_remote_request( 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId='.$playlist_id.'&key='.$api_key.'&order=date&maxResults=25',
      array(
          'method'     => 'GET'
        )
      );

After getting it I would like to have it in JSON so I am using:

      $json = wp_remote_retrieve_body($response);
      $json_encoded = json_encode($json, true);

If I am right this now should be a JSON representation of the supplied value. So I am getting:

{
    "kind": "youtube#playlistItemListResponse",
    "etag": "\"p4VTdlkQv3HQeTEaXevLePAydmU/Q2DmelXR9Ne48evrmJE9Q4yVvpU\"",
    "nextPageToken": "CAoQAE",
    "pageInfo": {
        "totalResults": 36,
        "resultsPerPage": 25
    },
    "items": [ ...

And I would like to store only the items. One would think that I can now access them via:

$json_encoded['items'];

And then store it into WordPress db like this:

      // if we have any items update the db with those results
      if ( isset ( $json_encoded['items'] )) {
        $videos['json'] = $json_encoded['items'];
        update_option( 'wpc_ylp_videos', $videos );
      }

Well, unfortunately, I get the following error:

Warning: Illegal string offset 'items' in /Users/tobias/Sites/videos.dev.cc/wp-content/plugins/videos/includes/videos.php on line 61
"

AND

Notice: Undefined index: json in /Users/tobias/Sites/videos.dev.cc/wp-content/plugins/videos/includes/videos.php on line 67

I am sure I am doing something wrong but can not wrap my head around this. How can I access the items object? Is my usage of json_encode right?

2
  • 2
    json_encode converts to a string. I believe you are looking for json_decode php.net/manual/en/function.json-decode.php Commented Dec 19, 2019 at 18:36
  • Ty Bailey, thanks, that was exactly the issue! Oh my. Commented Dec 19, 2019 at 19:43

1 Answer 1

1

For those of you that don't read comments; The answer is to use json_decode() instead of json_encode().

json_encode() converts to a string.

https://www.php.net/manual/en/function.json-decode.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.