Jump to content

Getting this error Notice: Trying to get property of non-object in, can someone please help?


avidorh

Recommended Posts

Hello,

 

I am new to PHP development, I am trying to change my php code to work with youtube API v3 instead of youtube API v2, instead of XML I need to work with JSON,

I did some changes and got this error:

Notice: Trying to get property of non-object in

 

Can someone please explain what does it mean and instruct me how to continue?

 

Thanks,

Avidor

Link to comment
Share on other sites

Plainly, it means what it says.  You're trying to get a value from a property of an object that doesn't exist.  Post the code you are using and a copy of the json array would be very helpful too and we can take a look. PS. make sure to use the forums code tags to post the code, it's the <> button in the posting window.

Link to comment
Share on other sites

Thanks, I will appreciate your help

 

here is the json array:

{
 "kind": "youtube#searchListResponse",
 "etag": "\"iDqJ1j7zKs4x3o3ZsFlBOwgWAHU/nTN8Qi2VMRoeekjg0xcBleX0lCo\"",
 "nextPageToken": "CAUQAA",
 "pageInfo": {
  "totalResults": 468,
  "resultsPerPage": 5
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"iDqJ1j7zKs4x3o3ZsFlBOwgWAHU/5DqDs_6XSMjfUWxD3BONxV7LIhU\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "33kl0iQByME"
   },
   "snippet": {
    "publishedAt": "2014-10-31T14:44:52.000Z",
    "channelId": "UCEGUP3TJJfMsEM_1y8iviSQ",
    "title": "The Power of $q by Dave Smith at ng-europe 2014",
    "description": "Dave Smith tells you everything you need to know about $q, promises with angular, nutella and bacon. Slides: http://goo.gl/LK7pHh.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/33kl0iQByME/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/33kl0iQByME/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/33kl0iQByME/hqdefault.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": "\"iDqJ1j7zKs4x3o3ZsFlBOwgWAHU/McNdbSHHAQ2P32rqGlvz8kpQRfk\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "cdG_T6ufcbE"
   },
   "snippet": {
    "publishedAt": "2013-11-05T21:30:54.000Z",
    "channelId": "UCutKx7_WN6r2iduofUe7mlw",
    "title": "AngularJS Promises with $q",
    "description": "Angular uses a subset of Q called $q for creating promises. =========================================== **Like what you saw? Be sure to ...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/cdG_T6ufcbE/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/cdG_T6ufcbE/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/cdG_T6ufcbE/hqdefault.jpg"
     }
    },
    "channelTitle": "joemaddalone",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": "\"iDqJ1j7zKs4x3o3ZsFlBOwgWAHU/o2hyDPkOe_jL4CtAu_wJSrpEBuo\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "uz0_zl6m07c"
   },
   "snippet": {
    "publishedAt": "2013-02-23T07:21:28.000Z",
    "channelId": "UCKW92i7iQFuNILqQOUOCrFw",
    "title": "AngularJS Promises with $q.mp4",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/uz0_zl6m07c/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/uz0_zl6m07c/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/uz0_zl6m07c/hqdefault.jpg"
     }
    },
    "channelTitle": "johnlindquist",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": "\"iDqJ1j7zKs4x3o3ZsFlBOwgWAHU/Qmy-6zT-6IZk-wYnqKrvldUs_P0\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "_Wl87xy-rLE"
   },
   "snippet": {
    "publishedAt": "2015-02-03T06:29:17.000Z",
    "channelId": "UCdlukvTGTdskK7bHuGhPrgA",
    "title": "#6.2 Using the Angular $q Library",
    "description": "Building a Application with AngularJS For Beginner.. How to Create Single Page with AngularJS, Create Application Wint AngularJS..",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/_Wl87xy-rLE/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/_Wl87xy-rLE/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/_Wl87xy-rLE/hqdefault.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": "\"iDqJ1j7zKs4x3o3ZsFlBOwgWAHU/GGCN3disXjmFC9IEmEIikyOPw84\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "FsOmdsICNYE"
   },
   "snippet": {
    "publishedAt": "2013-08-08T10:59:31.000Z",
    "channelId": "UClOccJXlB6zbCRAFigEc6EQ",
    "title": "Deferred and Promise objects in Angular js",
    "description": "Apologies for the shrunken video and poor sound. We'll do better next time! Overview Basics of Promise and deferred objects in Angular Combining promises ...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/FsOmdsICNYE/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/FsOmdsICNYE/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/FsOmdsICNYE/hqdefault.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  }
 ]
} 

and the php code:

<!DOCTYPE a PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--  _pre -->
	<html>
		<meta http-equiv="Content-Type" content="text/html; charset=utf8">
		<head>
			<style type="text/css">
				body {
					font-family:verdana,arial,sans-serif;
					font-size:10pt;
					margin:30px;
					background-color:#ffe97f;
				}
			</style>
			
			<script src="../js/jquery.min.js"></script>
			<script src="../js/actions.js"></script>
			<script type="text/javascript">
			function onFreeSearch(artistId, inEnglish)
			{
				//alert(artistId);
				var searchInput = document.getElementById("input_free_search");
				var searchTerm = searchInput.value;

				if (searchTerm == null || searchTerm == "") {
					alert("הכנס ערך לחיפוש");
					return;
				}

				var targetUrl = "artist_search.php?id=" + artistId + "&start=1&results=10&type=rel&searchTerm=" + searchTerm;
				if (inEnglish == true) {
					targetUrl += "&eng=1";
				} 
				
				parent.content.location.href = targetUrl;
					
			}
			
			function onAddClip(clipId) {
				var div = document.getElementById("div_" + clipId);					// Artist ID resides in each DIV
				var elementName = document.getElementById("name_" + clipId);		// Title input field
				var elementType = document.getElementById("type_" + clipId);		// Type combo
				var elementLyrics = document.getElementById("lyrics_" + clipId);	// Has lyrics check box
				var elementThumb = document.getElementById("thumb_" + clipId);	// Has lyrics check box
				var name = elementName.value;
				var type = elementType.selectedIndex;
				var lyrics = elementLyrics.checked ? 1 : 0;
				var artistId = div.getAttribute("name");
				var duration = elementThumb.getAttribute("duration");
										
				if (name != null && name != "") {
					$.post("../db/add_clip.php", { artistId: artistId, name: name,
						clipId: clipId, type: type, duration: duration, lyrics: lyrics },
							function(data) {
								if (data == "success") {
									div.style.background = "#a1f861";

									// Convert the add button into an update button
									var addButton = document.getElementById("addButton_" + clipId);
									addButton.value = "עדכן";
									addButton.onclick = function() { onUpdateClip(clipId); };

									// Update the artist songs list - add added clip to the end
									var existingSongs = document.getElementById("existing_songs");
									var newSong = document.createElement('div');
									newSong.value = name;
									existingSongs.appendChild(newSong);
									
								} else {
									alert(data);
								}
							});				
				} else {
					alert("שם השיר לא יכול להיות ריק");
				}				
			}			

			function onAddArtist(clipId)
			{
				$.post("../public/getallartists.php", null,
						function(data) {
							// Add dropdown to div
							var clipDiv = document.getElementById("div_" + clipId);
							var curHtml = clipDiv.innerHTML;						
							var selectHtml = "<select style='width:100px;' id='id_add_artist_" + clipId + "'>";
							var artistData = jQuery.parseJSON(data);
							var test = "";
						    $.each(artistData.artists, function (i, artist) {
						        selectHtml += "<option value='" + artist.id + "'>" + artist.name + "</option>";
						    });

							curHtml += selectHtml;
							curHtml += "<input type='button' value='הוסף' onClick=\"onAddArtistSelected('" + clipId + "')\"/>";
							clipDiv.innerHTML = curHtml;
						});						
			}			
			</script>			
		</head>
		<body style="direction:rtl" align="center">

<?php
require_once '../db/db_ozen_queries.php';
require_once '../utils/ui_utils.php';
require_once '../utils/ozen_ui_utils.php';
require_once '../utils/yt_utils.php';

// First initialize Database and increase load time limit
ob_start();
set_time_limit(600000);
OBaseDB::init('ozen');

$artist_id = isset($_GET["id"]) ? $_GET["id"] : null;
$start = isset($_GET["start"]) ? $_GET["start"] : 1;
$results = isset($_GET["results"]) ? $_GET["results"] : 10;
$type = isset($_GET["type"]) ? $_GET["type"] : "viewCount";
$search_term = isset($_GET["searchTerm"]) ? $_GET["searchTerm"] : null;
$eng = isset($_GET["eng"]) ? $_GET["eng"] : null;

if ($artist_id == null) {
	echo "Must provide id!";
	die();
} 

$artist = getArtist($artist_id);
if ($artist == null) {
	echo "id {$artist_id} Was not found in DB!";
	die();	
}

if ($search_term != null) {
	if ($eng != null) {
		echo "<h2>תוצאת חיפוש ל{$artist['ar_engname']} ($search_term)</h2>";
	} else {
		echo "<h2>תוצאת חיפוש ל{$artist['ar_hebname']} ($search_term)</h2>";
	}
} else {
	if ($eng != null) {
		echo "<h2>תוצאת חיפוש ל{$artist['ar_engname']}</h2>";
	} else {
		echo "<h2>תוצאת חיפוש ל{$artist['ar_hebname']}</h2>";
	}
}

// Update orderby type
if ($type == "rel") {
	$type = "relevance";	
}

$q = null;
// Run the search using the youtube API
if ($search_term != null) {
	if ($eng != null) {
		$q = str_replace(" ", "+", $search_term) . "+" . str_replace(" ", "+", $artist['ar_engname']);
	} else {
		$q = str_replace(" ", "+", $search_term) . "+" . str_replace(" ", "+", $artist['ar_hebname']);	
	} 
} else {
	if ($eng != null) {
		$q = str_replace(" ", "+", $artist['ar_engname']);
	} else {
		$q = str_replace(" ", "+", $artist['ar_hebname']);
	}
}

$q = urlencode($q);
 
//$feedURL = "http://gdata.youtube.com/feeds/api/videos?q={$q}&orderby={$type}&max-results={$results}&start-index={$start}";
$feedURL = "https://www.googleapis.com/youtube/v3/search?part=snippet%20&q={$q}&type=video&key=AIzaSyAtuq6UNWVrGvElJZxXOMGrB7mnh9yczuM";

//echo $feedURL;
//die();

//Call the API
$json_file = file_get_contents($feedURL);
// convert the string to a json object
$jfo = json_decode($json_file);
$counts = $jfo->pageInfo->resultsPerPage;
$total = $jfo->pageInfo->totalResults;
$startOffset = 1;
$endOffset = ($startOffset-1) + $counts;
if ($endOffset > $total) {
$endOffset = $total;
}

// read the title value
//$title = $jfo->result->title;
// copy the posts array to a php var
//$posts = $jfo->result->posts;
// listing posts
//foreach ($posts as $post) {
//    echo $post->title;

// Call the API
//$xml = simplexml_load_file($feedURL);
//
//$counts = $xml->children('http://a9.com/-/spec/opensearchrss/1.0/');
//$total = $counts->totalResults; 
//$startOffset = $counts->startIndex; 
//$endOffset = ($startOffset-1) + $counts->itemsPerPage;
//if ($endOffset > $total) {
//	$endOffset = $total;
//}

// Add top pager
getArtistSearchPager($start, $endOffset, $results, $total, $artist['ar_id'], $type, $search_term, $eng);

	echo "  חיפוש חופשי:" .
	createInputField("input_free_search", "", 150) .
	"<input type='button' value='חפש' onClick=\"onFreeSearch('{$artist_id}', false)\"/>" .
	"<input type='button' value='חפש באנגלית' onClick=\"onFreeSearch('{$artist_id}', true)\"/>";

// Show available artists songs on the left side
echo "<div id='existing_songs' style='background-color:#FFD700;width:300px;float:left;align:right;'>" .
	  "<h3>שירים קיימים</h3>";
$artist_songs = getArtistSongs($artist_id, 'name');

$number = 1;

if ($artist_songs != null) {
	while($artist_song = mysql_fetch_assoc($artist_songs)) {
		echo "<div align='right'>" . $number . ". " . $artist_song['song_hebname'] . "(" . getClipTypeText($artist_song['clip_type']) . ")</div><br>";
		$number++;
	}
} else {
	echo "עדיין לא הוגדרו שירים לאמן זה";
}

echo "</div>";

//echo "<div><div>test</div><br><div>test</div><br><div>test</div><br>";

// now show results
foreach ($json_file->kind as $kind) {
   // get nodes in media: namespace for media information
   $media = $kind->title('http://search.yahoo.com/mrss/');
        
   // get video player URL
   $attrs = $media->group->player->attributes();
   $watch = $attrs['url'];
   $ytid = extractYTId($watch);
   
   // Check to see if the clip already exists in the DB. If it exists, use an update instead of add
   $clip = getClip($ytid);
        
   // get video thumbnail
   $attrs = $media->group->thumbnail[0]->attributes();
   $thumbnail = $attrs['url'];

   $attrs = $media->group->content->attributes();
   $duration = $attrs['duration'];

   $bkcolor = null;
   
   if ($clip != null) {
   		$perf_artists = getPerfArtists($clip['perf_id']);
   		$same_artist = false;
   		if ($perf_artists != null) {
   			while($perf_artist = mysql_fetch_assoc($perf_artists)) {
   				if ($perf_artist['ar_id'] == $artist_id) {
   					$same_artist = true;
   				}
   			}	
   		}
   		
   		$bkcolor = $same_artist == true ? "#a1f861" : "#0094FF";
   } else {
   		$bkcolor = "#ffe97f";
   } 
   
   echo "<div style='background-color:{$bkcolor};' id='div_{$ytid}' name='{$artist_id}' align='right' height='80'>" . getYTThumb($ytid, $duration) .
   		createInputField("name_{$ytid}", $clip != null ? $clip['song_hebname'] : $media->group->title) .
   		createClipTypeSelector($ytid, $clip != null ? $clip['clip_type'] : 0) .
   		createLyricsCheckbox($ytid, $clip != null ? $clip['clip_lyrics'] : false) .
   		($clip != null ? "<input type='button' value='עדכן' style='margin-right:50px;' onClick=\"onUpdateClip('{$clip['clip_ytid']}')\"/>" :
   		"<input id='addButton_{$ytid}' type='button' value='הוסף' style='margin-right:50px;' onClick=\"onAddClip('{$ytid}')\"/>") . 
		"<input type='button' value='הוסף אמן' onClick=\"onAddArtist('{$clip['clip_ytid']}')\"/>" .
		//"<a target='leftMenu' href='song_lyrics.php?songid={$song['song_id']}&arid=" . urlencode($artist['ar_id']) . "'><input type='button' value='מילים' /></a>" .

   "</div><br>";
}

//echo "</div>";

// Add bottom pager
getArtistSearchPager($start, $endOffset, $results, $total, $artist['ar_id'], $type, $search_term); 
Link to comment
Share on other sites

$json_file = file_get_contents($feedURL);
This is probably failing. You must turn on allow_fopen_url in your PHP.ini to use URL's in file_get_contents().

 

An alternative is to use CURL, like so:

$ch = curl_init('https://www.googleapis.com/youtube/v3/search?part=snippet%20&q={$q}&type=video&key=AIzaSyAtuq6UNWVrGvElJZxXOMGrB7mnh9yczuM');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$json_file = curl_exec($ch);

curl_close($ch);

$jfo = json_decode($json_file);

if (json_last_error() == JSON_ERROR_NONE) {
	// good to go
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.