Shuffle youtube IDs - php

am new to php and I was wondering how I could retrieve shuffled YouTube IDs..
Here is what I mean..
$playlist_id = "PLB9DAD6B9EDAEE7BC";
$cont = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/playlists/'.$playlist_id.'/?v=2&alt=json&feature=plcp'));
$feed = $cont->feed->entry;
if(count($feed)) {
foreach($feed as $item) {
$title = $item->title->{'$t'};
$desc = $item->{'media$group'}->{'media$description'}->{'$t'};
$id = $item->{'media$group'}->{'yt$videoid'}->{'$t'};
}
}
This basically fetches the id, title and description from the playlist, how can I shuffle the $id to give me unique unrepeated values so that I can later on use it here?
<iframe ... src="http://www.youtube.com/embed/<?= $id ?>" allowfullscreen></iframe>
My goal is to refresh the page to get a new video each time I visit it and reset itself when it's over (or just continue picking unique values)
Thank you in advance, a lot..

You can store all the feed videos in an array and then use array_rand to get a random entry of the array.
See http://php.net/manual/de/function.array-rand.php for function reference.
Be aware that array_rand return a single key when used with default settings but it will deliver an array of keys if you choose to select more then a single random entry.
EDIT: Added cookie so the video is REAL random-unique
Code snippet:
$playlist_id = "PLB9DAD6B9EDAEE7BC";
$cont = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/playlists/'.$playlist_id.'/?v=2&alt=json&feature=plcp'));
$feed = $cont->feed->entry;
$youtubeVideos = array();
if(count($feed))
{
foreach($feed as $item)
{
// build video array
$video = array();
$video['title'] = $item->title->{'$t'};
$video['desc'] = $item->{'media$group'}->{'media$description'}->{'$t'};
$video['id'] = $item->{'media$group'}->{'yt$videoid'}->{'$t'};
// push it into collection
$youtubeVideos[$video['id']] = $video;
}
}
$seenVideos=array();
$lastSeenVideo='';
// only get diff array if the cookies are set (= not first page view)
if(isset($_COOKIE['seen_youtube_videos']) && isset($_COOKIE['last_youtube_video']))
{
$lastSeenVideo=$_COOKIE['last_youtube_video'];
$seenVideos=unserialize($_COOKIE['seen_youtube_videos']);
$diffArr=$youtubeVideos;
foreach($seenVideos as $vidId)
unset($diffArr[$vidId]);
if(count($diffArr)>0)
{
// set difference for searching only
$youtubeVideos=$diffArr;
}
else
{
// if we did show all videos, reset everything
setcookie('seen_youtube_videos', '');
setcookie('last_youtube_video', '');
$seenVideos = array();
}
}
$randomizedKey = array_rand($youtubeVideos);
$randomVideo = $youtubeVideos[$randomizedKey];
do
{
$randomizedKey = array_rand($youtubeVideos);
$randomVideo = $youtubeVideos[$randomizedKey];
}
while($randomVideo['id'] == $lastSeenVideo);
$seenVideos[] = $randomVideo['id'];
setcookie('seen_youtube_videos', serialize($seenVideos));
setcookie('last_youtube_video', $randomVideo['id']);
// do stuff with $randomVideo

Related

Wordpress not displaying API data

I'm calling on an API using Wordpress (widget).
But for some reason, it's not letting me display nested objects like so:
private function get_request($username) {
$url = wp_remote_get("https://api.github.com/users/essxiv/repos");
$response = json_decode(stripslashes($url['body']));
$nested_objs = $response[0]['id'];
print_r($nested_objs);
}
I've also tried to print_r($response[0]['username']);
Everytime I tried to load my localhost Wordpress, it gives me a different looking UI, with NO Admin Header and the border of the page is orange and not black..
I'm just stumped and really need to display these nested object's data.
What am I doing wrong? How do I get the data printed?
Solution:
Apparently PHP does it a little differently:
private function get_request($username) {
$url = wp_remote_get("https://api.github.com/users/essxiv/repos");
$response = json_decode(stripslashes($url['body']));
$name = $response[0]->{'name'};
$id = $response[0]->{'id'};
$owner = $response[0]->{'owner'};
print_r($name);
print_r($id);
print_r($owner);
}
If you want to find a nested object key/value it would look something like this:
$owner = $response[0]->{'owner'}->{'login'};
Use a foreach loop..
function get_request($username='') {
$url = wp_remote_get("https://api.github.com/users/essxiv/repos");
$response = json_decode(stripslashes($url['body']));
foreach ($response as $key => $value) {
echo $value->id;
// $value->login;
// $value->avatar_url;
}
}

Pulling NHL Standings from XML Table with PHP

I'm working on a project in which I pull various statistics about the NHL and inserting them into an SQL table. Presently, I'm working on the scraping phase, and have found an XML parser that I've implemented, but I cannot for the life of me figure out how to pull information from it. The table can be found here -> http://www.tsn.ca/datafiles/XML/NHL/standings.xml.
The parser supposedly generates a multi-dimmensional array, and I'm simply trying to pull all the stats from the "info-teams" section, but I have no idea how to pull that information from the array. How would I go about pulling the number of wins Montreal has? (Solely as an example for the rest of the stats)
This is what the page currently looks like -> http://mattegener.me/school/standings.php
here's the code:
<?php
$strYourXML = "http://www.tsn.ca/datafiles/XML/NHL/standings.xml";
$fh = fopen($strYourXML, 'r');
$dummy = fgets($fh);
$contents = '';
while ($line = fgets($fh)) $contents.=$line;
fclose($fh);
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
print_r($arrOutput[0]); //This print outs the array.
class xml2Array {
var $arrOutput = array();
var $resParser;
var $strXmlData;
function parse($strInputXML) {
$this->resParser = xml_parser_create ();
xml_set_object($this->resParser,$this);
xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");
xml_set_character_data_handler($this->resParser, "tagData");
$this->strXmlData = xml_parse($this->resParser,$strInputXML );
if(!$this->strXmlData) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->resParser)),
xml_get_current_line_number($this->resParser)));
}
xml_parser_free($this->resParser);
return $this->arrOutput;
}
function tagOpen($parser, $name, $attrs) {
$tag=array("name"=>$name,"attrs"=>$attrs);
array_push($this->arrOutput,$tag);
}
function tagData($parser, $tagData) {
if(trim($tagData)) {
if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
}
else {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
}
}
}
function tagClosed($parser, $name) {
$this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this- >arrOutput)-1];
array_pop($this->arrOutput);
}
}
?>
add this search function to your class and play with this code
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
// first param is always 0
// second is 'children' unless you need info like last updated date
// third is which statistics category you want for example
// 6 => the array you want that has wins and losses
print_r($arrOutput[0]['children'][6]);
//using the search function if key NAME is Montreal in the whole array
//result will be montreals array
$search_result = $objXML->search($arrOutput, 'NAME', 'Montreal');
//first param is always 0
//second is key name
echo $search_result[0]['WINS'];
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, $this->search($subarray, $key, $value));
}
return $results;
}
Beware
this search function is case sensitive it needs modifications like match to
a percentage the key or value changing capital M in montreal to lowercase will be empty
Here is the code I sent you working in action. Pulling the data from the same link you are using also
http://sjsharktank.com/standings.php
I have actually used the same exact XML file for my own school project. I used DOM Document. The foreach loop would get the value of each attribute of team-standing and store the values. The code will clear the contents of the table standings and then re-insert the data. I guess you could do an update statement, but this assumes you never did any data entry into the table.
try {
$db = new PDO('sqlite:../../SharksDB/SharksDB');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "DELETE FROM standings";
$result = $db->query($query);
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://www.tsn.ca/datafiles/XML/NHL/standings.xml');
$searchNode = $xmlDoc->getElementsByTagName( "team-standing" );
foreach ($searchNode as $searchNode) {
$teamID = $searchNode->getAttribute('id');
$name = $searchNode->getAttribute('name');
$wins = $searchNode->getAttribute('wins');
$losses = $searchNode->getAttribute('losses');
$ot = $searchNode->getAttribute('overtime');
$points = $searchNode->getAttribute('points');
$goalsFor = $searchNode->getAttribute('goalsFor');
$goalsAgainst = $searchNode->getAttribute('goalsAgainst');
$confID = $searchNode->getAttribute('conf-id');
$divID = $searchNode->getAttribute('division-id');
$query = "INSERT INTO standings ('teamid','confid','divid','name','wins','losses','otl','pts','gf','ga')
VALUES ('$teamID','$confID','$divID','$name','$wins','$losses','$ot','$points','$goalsFor','$goalsAgainst')";
$result= $db->query($query);
}

Retrieve all values in my loop and format it to json

I'm trying to build a page which queries my database and then formats output so another webservice/page can access the data.
Ideally I wanted to explore having the data in JSON format, but that is not working. The other problem I have which is more major than the JSON not working is, if I have 3 records in $reportsResult, only the last one is displayed.
Anyone with some help please. Oh do I also need to print_r for the external webpage to retrieve the data or is there a better way?
class Pupil {
public $FirstName = "";
public $LastName = "";
}
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
}
json_encode($Pupil);
OK managed to figure out how how to get all records from the loop, but its still not displaying in json format when I do a print_r - am I missing something?
$AllPupils = array();
foreach($reportsResult->getRecords() as $reportRecord)
{
$Pupil = new Pupil();
$Pupil->FamID = $reportRecord->getField('FName');
$Pupil->ChildName = $reportRecord->getField('SName');
array_push($AllPupils, $Pupil);
}
json_encode($AllPupils);
Everytime your foreach loop starts again, it will override your $Pupil variable.
Try an array instead:
$Pupil = array()
$i = 0;
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil[$i] = new Pupil();
$Pupil[$i]->FirstName = $reportRecord->getField('FName');
$Pupil[$i]->LastName = $reportRecord->getField('SName');
$i++;
}
echo json_encode($Pupil);
Edit: mikemackintosh's solution should also work and could be a little bit faster (depending on the size of your foreach loop).
To display the results you need to echo your data (not only json_encode).
You will probably run into issues since json_encode wont handle the whole object. for that, you may want to serialize the $Pupil object.
Something like below may work for you though. It will assign the values to a returned array, which will allow json_encode to execute gracefully:
class Pupil {
public $FirstName = "";
public $LastName = "";
public function getAttr(){
return array("FirstName" => $this->FirstName, "LastName" => $this->LastName);
}
}
$json = array();
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
$json[] = $Pupil->getAttr();
}
echo json_encode($json);
I am not sure why you have that class defined, but you know what in your for each have something like
foreach ($reportsResult->getRecords() as $key => $record) {
$data[$key]['firstname'] = $record->getField('Fname');
$data[$key]['lastname'] = $record->getField('Sname');
}
And then you can check the final array using print_r
and while output you can simply do a print json_encode($data) and it will give you a json string of all the items in the data array.
In php (at least), json_encode takes an array as parameter.
Therefore you should add a constructor to your class
function __construct($first, $last)
{
this.$FirstName = $first;
this.$LastName = $last;
}
and one for getting the full name as an array, ready to be jsoned
function getNameArray()
{
$nameArray = array();
$nameArray['firstName'] = this.$FirstName;
$nameArray['lastName'] = this.$LastName;
return $nameArray;
}
then in that foreach you build another array with all the pupils
$pupils = array();
foreach (bla bla)
{
$first = $reportRecord->getField('FName');
$last = $reportRecord->getField('SName');
$Pupil = new Pupil($first, $last);
array_push($pupils, $pupil.getNameArray());
}
finally, you have everything preped up
json_encode($pupils);
I'm sure there's other ways to debug your stuff, I use print_r mainly also.

How to capture href links and replace this via PHP

I have a php variable with some html content, and some href links. I need to capture this links, save to a DB and replace it with the id of the row that I just saved (is to track how many people follows that link in a newsletter application).
Basicatly I need to do the 2 functions in the example (some_function_to_save_the_links_to_array and some_function_to_save_the_links_to_array).
Thank you a lot for your help!
Example:
$var = "<html><body><h1>This is the newsletter</h1><p>Here I have <a href='http://www.google.com'>Some links</a> in the body of this <a href='http://www.yahoo.com'>Newsletter</a> and I want to extract their.</body></html>";
//Here I just no know how to do this, but I need to save http://www.google.com and http://www.yahoo.com to, maybe, an array, and save this array in a mysql db.
some_function_to_save_the_links_to_array;
while (THERE ARE VALUES IN THE ARRAY OF THE LINKS){
save $array['X'] to db //(I already know how to do it, this is not the problem)
$id = last inserted row in db //I know how to do it also
function_to_replace_the_links_for_the_id;
}
echo $var;
And this is the echo:
<html><body><h1>This is the newsletter</h1><p>Here I have <a href='http://www.mysite.com/link.php?id=1'>Some links</a> in the body of this <a href='http://www.mysite.com/link.php?id=1'>Newsletter</a> and I want to extract their.
<?php
function captureLink($content)
{
$links = array();
$pattern = "/<a\s+href=[\"\']([^>]+?)[\"\']/iU";
if(preg_match_all($pattern,$content,$matches)) {
for($i = 0;$link = $matches[$i][1];$i++)
array_push($links,$link);
}
return $links;
}
function insertLinksToDb(array $links)
{
$linksDb = array();
foreach($links as $link) {
$hash_link = md5($link);
$sql = "SELECT (id) FROM links WHERE hash LIKE :hash";
$sth = $dbh->prepare($sql);
$sth->bindValue(':hash',$hash_link,PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
if(!empty($result)) {
$id = $result['id'];
$linksDb[$id] = $link;
} else {
$sql = " INSERT INTO links (hash,link) VALUES(:hash,:link);";
$sth = $dbh->prepare($sql);
$sth->execute(array(':hash'=>$hash_link,':link',$link));
$linksDb[PDO::lastInsertId] = $link;
}
}
return $linksDb;
}
function normallizeLinks($content,array $links)
{
foreach($links as $id => $link) {
//str_replace working faster than strtr
$content = str_replace($link,'/links.php?id='.$id,$content);
}
return $content;
}

building an associative array

This is going to be my first time building an associative array. And if anyone can help me I would be grateful.
Basically, I want to loop through a directory of XML files. I want to find out if a certain editor was the editor of this file, and if the query is true, I would like to grab two pieces of information and achieve the result of an associate array with those two pieces of information for every case where the editor's name is found.
So here's what I have got so far:
function getTitleandID($editorName) {
$listofTitlesandIDs = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
if ($editorName == $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()"))
{
$title = $xmldoc->xpath("//tei:teiHeader/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id[1]");
$listofTitlesandIDs[] = //I don't know what to do here
}
else
{
$listofTitlesandIDs = null;
}
}
return $listofTitlesandIDs
}
This is about where I get stuck. I'd like to be able have $listofTitlesandIDs as an associative array where I could call up the values for two different keys, e.g. $listofTitlesandIDs['title'] and $listofTitlesandIDs[$id]
So that's about it. I'm grateful for any help you have time to provide.
Well I'm sure this is a little clumsy (the result of an amateur) but it has given me the result I want.
function getTitlesandIDs($EditorName) //gets titles and IDs for given author
{
$list = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$title = $xmldoc->xpath("//tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id");
$editorName = $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()")
if ($editorName[0] == "$EditorName")
{
$result = array("title"=>$title[0], "id"=>$id[0]);
$list[] = $result;
}
}
return $list;
}
With this I can call the function $list = getTitlesandIDs('John Doe') and then access both the title and id in the associative array for each instance. Like so:
foreach ($list as $instance)
{
echo $instance['title'];
echo $instance['id'];
}
Maybe that will help somebody some day -- let me know if you have any advice on making this more elegant.
$listofTitlesandIDs[$id] = $title;
You should loop over the array then using the foreach loop.

Categories