Accessing a specific nested value from Spotify Artists array - php

I am using jwilsson's spotify-web-api-php to return data from the Spotify API using PHP.
Also I'm using digitalnature's php-ref to return info about variables.
This is my (terrible) code:
// https://stackoverflow.com/questions/4345554/convert-a-php-object-to-an-associative-array
function objectToArray($r)
{
if (is_object($r)) {
if (method_exists($r, 'toArray')) {
return $r->toArray(); // returns result directly
} else {
$r = get_object_vars($r);
}
}
if (is_array($r)) {
$r = array_map(__FUNCTION__, $r); // recursive function call
}
return $r;
}
$session = new SpotifyWebAPI\Session(
'aaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbb'
);
$session->requestCredentialsToken();
$accessToken = $session->getAccessToken();
$str = $_POST['str'];
$str_length = strlen($_POST['str']);
$html = null;
$api = new SpotifyWebAPI\SpotifyWebAPI();
$api->setAccessToken($accessToken);
$search = $api->search('fugazi','artist');
$search_array = objectToArray($search);
r($search_array);
// loop through the results
foreach($search_array['artists']['items'] as $item) {
// artist name
$artist_name = $item['name'];
$html .= "<h2>$artist_name</h2>";
// genres
foreach($item['genres'] as $genre) {
$html .= " <span class='code'>$genre</span> ";
}
// $v2 = $item['images']['0']['height'];
// r($v2);
}
This is what the php-ref shows the $search_array to look like:
Or as plain text: https://0bin.net/paste/iPYfn2M6#Pt8l-a9i9el0TVnZsDTA8wlbe/t0CGSIsp4bds0IZyT
I would like to access the attributes for the first element in the images array for each artist returned.
I tried via this line:
$v2 = $item['images']['0']['height'];
But the following error was returned:
PHP Notice: Undefined offset: 0 in C:\Websites\spotify\search.php on line 68
PHP Notice: Trying to access array offset on value of type null in C:\Websites\spotify\search.php on line 68
I have searched around that error but I can't get my head around the correct syntax to use in this example.
Sorry for my lack of understanding.

Related

Undefined Variable - PHP Code Snippet In Wordpress

I know this has been answered many times, but I don't know why I'm getting this error:
Notice: Undefined variable: urlfilter in
/home/mjburkel/public_html/allxxcars/wp-content/plugins/insert-php/includes/shortcodes/shortcode-php.php(52)
: eval()'d code on line 75
I know that this would normally be if the variable is not defined yet, but I am declaring it, thus I'm not exactly sure what the issue is. here is my code..note this is php code that I'm inserting into a Wordpress PHP snippet plugin...so, not sure if that plugin is inserting some weird code or not reading it properly maybe?
<?php /* Template Name: Completed W517 */
error_reporting(E_ALL); // Turn on all errors, warnings and notices for easier debugging
// API request variables
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call
$version = '1.0.0'; // API version supported by your application
$appid = 'XXX'; // Replace with your own AppID
$globalid = 'EBAY-US'; // Global ID of the eBay site you want to search (e.g., EBAY-DE)
$query = 'ford mustang'; // You may want to supply your own query
$safequery = urlencode($query); // Make the query URL-friendly
$i = '0'; // Initialize the item filter index to 0
// Create a PHP array of the item filters you want to use in your request
$filterarray =
array(
array(
'name' => 'MaxPrice',
'value' => '1000000',
'paramName' => 'Currency',
'paramValue' => 'USD'),
array(
'name' => 'MinPrice',
'value' => '100',
'paramName' => 'Currency',
'paramValue' => 'USD'),
array(
'name' => 'SoldItemsOnly',
'value' => 'true'),
);
function CurrencyFormat($number)
{
$decimalplaces = 2;
$decimalcharacter = '.';
$thousandseparater = ',';
return number_format($number,$decimalplaces,$decimalcharacter,$thousandseparater);
}
// Generates an indexed URL snippet from the array of item filters
function buildURLArray ($filterarray) {
global $urlfilter="";
global $i="";
// Iterate through each filter in the array
foreach($filterarray as $itemfilter) {
// Iterate through each key in the filter
foreach ($itemfilter as $key =>$value) {
if(is_array($value)) {
foreach($value as $j => $content) { // Index the key for each value
$urlfilter .= "&itemFilter($i).$key($j)=$content";
}
}
else {
if($value != "") {
$urlfilter .= "&itemFilter($i).$key=$value";
}
}
}
$i++;
}
return "$urlfilter";
} // End of buildURLArray function
// Build the indexed item filter URL snippet
buildURLArray($filterarray);
// Construct the findItemsByKeywords HTTP GET call
$apicall = "$endpoint?";
$apicall .= "OPERATION-NAME=findCompletedItems";
$apicall .= "&SERVICE-VERSION=$version";
$apicall .= "&SECURITY-APPNAME=$appid";
$apicall .= "&GLOBAL-ID=$globalid";
$apicall .= "&keywords=$safequery";
$apicall .= "&categoryId=213";
$apicall .= "&paginationInput.entriesPerPage=20";
$apicall .= "$urlfilter";
// Load the call and capture the document returned by eBay API
$resp = simplexml_load_file($apicall);
// Check to see if the request was successful, else print an error
if ($resp->ack == "Success") {
$results = '';
// If the response was loaded, parse it and build links
foreach($resp->searchResult->item as $item) {
if ($item->pictureURLLarge) {
$pic = $item->pictureURLLarge;
} else {
$pic = $item->galleryURL;
}
$link = $item->viewItemURL;
$title = $item->title;
$price = $item->sellingStatus->convertedCurrentPrice;
$bids = $item->sellingStatus->bidCount;
$end = $item->listingInfo->endTime;
$fixed = date('M-d-Y', strtotime($end));
if(empty($bids)){
$bids = 0;
}
// For each SearchResultItem node, build a link and append it to $results
$results .= "<div class=\"item\"><div class=\"ui small image\"><img height=\"200px\" width=\"130px\" src=\"$pic\"></div><div class=\"content\"><div class=\"header\">$title</div><div class=\"meta\" style=\"margin-top:.1em\"><span class=\"price\"></span><div class=\"extra\">Sold Date: $fixed</div><div class=\"extra\"><button class=\"ui button\"><b>Number of Bids:</b> $bids </button></div><div class=\"extra\"><button class=\"ui orange button\">Sold Price: $$price</button></div><div class=\"description\"></div></div></div></div>";
}
}
// If the response does not indicate 'Success,' print an error
else {
$results = "<h3>Oops! The request was not successful. Make sure you are using a valid ";
$results .= "AppID for the Production environment.</h3>";
}
?>
What version of PHP are you using? You should actually be getting a syntax error when you first declare $urlfilter in your buildURLArray() function:
php: error - unexpected '=', expecting ',' or ';' in Standard input code
Because you're not supposed to be defining a variable after invoking it with the global keyword.
Basically, you should replace the beginning of your function with this:
// Generates an indexed URL snippet from the array of item filters
function buildURLArray ($filterarray) {
global $urlfilter, $i; // Load global variables
//…
}
And $urlfilter should be defined in the global scope, not the function scope. You could probably just put it under $i = '0'; // Initialize the item filter index to 0

Fatal Error occurring while passing html data in array using simple html dom php

I am trying to extract data using simple html dom and it works fine when i am passing html file or url to it i-e :-
$html = file_get_html('sv.html');
$foo = $html->find('p[plaintext^=EDUCATION AND TRAINING]');
$items3 = array();
foreach ($pinfo as $keypi) {
# code...
//var_dump($key);
//print_r($key);
while ( $keypi->nextSibling() ) {
if ( $keypi->nextSibling() == TRUE) {
//echo $key->nextSibling();
$keypi = $keypi->nextSibling();
$varcpi = $keypi->plaintext;
//$cnt++;
//echo "cnt=$cnt<br><br><br>";
}
if ( trim($varcpi) == "JOB APPLIED FOR" ){
break;
}
$items3[] = $varcpi;
}
}
$trimmedArray = array_map('trim', $items3);
$b = array_values(array_filter($trimmedArray));
var_dump($b);
Problem occurs when i pass html file in array as i am trying to pass it html data that was converted from pdf using PDFTOHTML (a php library) in code given below $page contains html data if i echo $page it's showing html accurate but when i pass it as array to simple html dom it's not working :-
include 'vendor/autoload.php';
$pdf = new \TonchikTm\PdfToHtml\Pdf('cv.pdf', [
'pdftohtml_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdftohtml.exe',
'pdfinfo_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdfinfo.exe'
]);
foreach ($pdf->getHtml()->getAllPages() as $page) {
$my_array[] = $page . '<br/>';
}
//$html = file_get_html('sv.html');
$pinfo = $my_array->find('p[plaintext^=PERSONAL INFORMATION]');
where $my_array[] contains html data is and showing accurate results but when i pass it to simple html dom here :-
$pinfo = $my_array->find('p[plaintext^=PERSONAL INFORMATION]');
instead of this:-
$html = file_get_html('sv.html');
it shows error :-
( ! ) Fatal error: Call to a member function find() on array in C:\wamp64\www\new\upload.php on line 56
i have tried using str_get_html which does not any error but also it's not showing any results :-
foreach ($pdf->getHtml()->getAllPages() as $page) {
$html = str_get_html($page);
$pinfo = $html->find('p[plaintext^=PERSONAL INFORMATION]');
$items3 = array();
foreach ($pinfo as $keypi) {
# code...
//var_dump($key);
//print_r($key);
while ( $keypi->nextSibling() ) {
if ( $keypi->nextSibling() == TRUE) {
//echo $key->nextSibling();
$keypi = $keypi->nextSibling();
$varcpi = $keypi->plaintext;
//$cnt++;
//echo "cnt=$cnt<br><br><br>";
}
if ( trim($varcpi) == "JOB APPLIED FOR" ){
break;
}
// echo $varc;
$items3[] = $varcpi;
}
}
$trimmedArray = array_map('trim', $items3);
$b = array_values(array_filter($trimmedArray));
var_dump($b);
}
Output:-
C:\wamp64\www\new\upload.php:81:
array (size=0)
empty
C:\wamp64\www\new\upload.php:81:
array (size=0)
empty
It would be great if anyone help me out here!!!

Illegal string offset 'key'

I have this code:
// Champion name and splash art
$endpointChampion = file_get_contents("https://global.api.riotgames.com/api/lol/static-data/BR/v1.2/champion/".$championMastery."?api_key=MYKEY");
$jsonChampion = json_decode($endpointChampion, true);
foreach ($jsonChampion as $champion) {
if (isset($jsonChampion['key'])) {
$championKey = $champion['key'];
}
}
But this $championKey variable returns "o" and 3 warnings are prompted on screen:
Warning: Illegal string offset 'key' in E:\xampp\htdocs\riot\index.php on line 41
I also tried to validate the entry, using isset() but seems not work properly.
The $championMastery is retrieved here:
$endpointMastery = file_get_contents("https://br.api.riotgames.com/championmastery/location/BR1/player/8083198/champions?api_key=MYKEY");
$jsonMastery = json_decode($endpointMastery, true);
foreach ($jsonMastery as $mastery) {
$championMastery = $mastery['championId'];
$masteryLevel = $mastery['championLevel'];
}
You are getting error because API returns one dimensional array and $champion is string value in foreach ($jsonChampion as $champion). Following can be fix:
foreach ($jsonChampion as $champion) {
if (isset($jsonChampion['key'])) {
$championKey = $jsonChampion['key'];
}
}
BTW,
$jsonChampion is one dimensional Array so you can retrieve $championKey without writing foreach loop as follows:
if(is_array($jsonChampion) && isset($jsonChampion['key'])){
$championKey = $jsonChampion['key'];
}

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);
}

PHP Notice: Undefined index: url

Any reason why i'm getting this error
PHP Notice: Undefined index: url on line 40
From my code the code is used to grab link for movies from a site but as i try to grab the link i get that error so could someone point me in the right direction on solving the issue.
public function getMovieEmbeds($title) {
$misc = new Misc();
//Step1 find key
$movie_url = null;
$html = file_get_html('http://www.primewire.ag/');
$elements = $html->find('input[name=key]',0);
$key = null;
if(!is_null($elements)){
$key = $elements->value;
}
if(is_null($key)){
return array();
}
//Step2 do search...
$search = urlencode($title);
$html = file_get_html("http://www.primewire.ag/index.php?search_keywords=$search&key=$key&search_section=1");
$elements = $html->find(".index_item h2");
if(!is_null($elements)){
foreach($elements as $element){
$element_title = strtolower(strip_tags(trim(preg_replace('/\s*\([^)]*\)/', '', $element->innertext))));
if ($element_title == strtolower(trim($title))) {
$parent = $element->parent();
$movie_url = "http://primewire.ag".$parent->href;
break;
}
}
}
if (is_null($movie_url)) {
return array();
}
//Step3 get embeds
$html = file_get_html($movie_url);
$elements = $html->find(".movie_version_link a");
if(!is_null($elements)){
foreach($elements as $element){
$encoded_url = "http://primewire.ag".$element->href;
$query = parse_url($encoded_url, PHP_URL_QUERY);
parse_str($query,$op);
error came from ---> $link = base64_decode($op["url"]); <--- here
if(strpos($link, "affbuzzads")===false && strpos($link, "webtrackerplus")===false){
$embed = $misc->buildEmbed($link);
if ($embed) {
$embeds[] = array(
"embed" => $embed,
"link" => $link,
"language" => "ENG",
);
}
}
}
return $embeds;
}
return array();
}
could some one please help me it would be most helpful
parse_str returns an array of the parameters on a URL, as if it was in the $_GET array.
It would only contain a 'url' value if the url you used had a parameter 'url'
E.g. it was along the lines of:
http://example.com/?url=urlvalue
Therefore, if $element->href (and therefore $encoded_url and $query) does not contain a parameter named 'url' in it you'll not get an index in the $op array of 'url'
See the documentation here: http://us1.php.net/manual/en/function.parse-str.php

Categories