Is it possible to use an if isset on an item in an array?
example:
if (isset($cityWeatherRssUrls[0])
I receive the following warning when doing so.
Warning: get_temperature() [function.get-temperature]: Node no longer exists in C:\xampp\htdocs\Twinz\includes\getWeather.php on line 51
Line 51 begins after the //Pull temperature comment from the function get_temperature(SimpleXMLElement $xml) in my getWeather.php script.
Below contains all the relevant scripts and functions
cityConfig.php - is used for declaring all the cities and corresponding URL's to yahoo's weather XML.
// Define arrays //
$cities = array();
$cityWeatherRssUrls = array();
// Feed URL's //
$yahooWeather = 'http://weather.yahooapis.com/forecastrss?p=';
// City 1 //
$city = 'London';
$cityWeatherRssUrl = $yahooWeather . $cityWeatherFeedCode . '&u=c';
array_push($cities, $city);
array_push($cityWeatherRssUrls, $cityWeatherRssUrl);
getWeather.php - contains functions for parsing XML tag contents and displaying the content
function get_current_weather($weatherRssUrl) {
// Get XML data from source
if (isset($weatherRssUrl)) {
$feed = $weatherRssUrl;
} else {
echo 'Feed not found. Check URL';
}
checkFeedExists($feed);
$xml = new SimpleXmlElement($feed);
$weather = get_temperature($xml);
return $weather;
}
function get_temperature(SimpleXMLElement $xml) {
// Pull temperature from XML
$weather['temp'] = $xml->channel->item->children('yweather', TRUE)->condition->attributes()->temp;
echo round($weather['temp']) . "°C" . "<br />";
return $temp;
}
//Display City Content //
function displayCityContent($cityWeatherRssUrls, $columnSubheading) {
if (isset($cityWeatherRssUrls)) {
echo get_current_weather($cityWeatherRssUrls);
echo $columnSubheading;
echo get_forecast_weather($cityWeatherRssUrls);
echo '<br />';
} else {
content_unavailable();
}
}
threeColumnContainer.php - is used to display Weather contents inside a html column
<ul class="columns">
<li class="col1">
<h3><?php
if (isset($column1Heading)) {
echo $column1Heading;
}
?></h3>
<p>
<?php
if (isset($cityWeatherRssUrls[0]) && ($currentPage == 1)) {
echo displayCityContent($cityWeatherRssUrls[0], $columnSubheading);
I can confirm that $cityWeatherRssUrls[0] contains the weather url for London because if I increment the array $cityWeatherRssUrls[1] I receive the a message saying that the feed cannot be found.
Any thoughts?
Thanks in advance
There were quite a few key concepts missing from your code, but hopefully the following will help you fix your code...
<?php
function get_feed($feed_url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $feed_url);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$rss = curl_exec($ch);
curl_close($ch);
return $rss;
}
function get_weather_feed_xml($feed_url = null)
{
$feed = get_feed($feed_url);
return new SimpleXmlElement($feed);
}
function get_temperature($feed_url)
{
if(stripos($feed_url, 'yahooapis') !== false)
{
return get_temperature_yahoo($feed_url);
}
return false;
}
function get_temperature_yahoo($feed_url)
{
if(($xml = get_weather_feed_xml($feed_url)) !== false)
{
return (float)$xml->channel->item->children('yweather', true)->condition->attributes()->temp;
}
return false;
}
function get_city_temperature($city_name, $city_WOEID, $feeds)
{
$results = array();
foreach($feeds as $feed_name => $feed_url)
{
$feed_url = str_replace(array('{WOEID}', '{NAME}'), array($city_WOEID, $city_name), $feed_url);
$results[$feed_name] = get_temperature($feed_url);
}
return $results;
}
function get_cities_temperature($cities, $feeds)
{
$results = array();
foreach($cities as $city_name => $city_WOEID)
{
$results[$city_name] = get_city_temperature($city_name, $city_WOEID, $feeds);
}
return $results;
}
// -------------------------------
$cities = array(
'London' => 44418,
'Los Angeles' => 2442047,
'Sydney' => 1105779,
);
$feeds = array(
'Yahoo' => 'http://weather.yahooapis.com/forecastrss?u=c&w={WOEID}',
);
$check = get_cities_temperature($cities, $feeds);
echo '<pre>';
print_r($check);
echo '</pre>';
Related
From my PHP application, I want to update the inventory_policy (continue/deny) of all products using API. Is there any way to do so without a loop?
I did not find any way to update it at once. Hence, I have updated it one by one. Please have the code below.
public function update_inventory_policy_for_all_item($inventory_policy, $page_info=null){
$response = $this->do_get("/admin/api/2021-04/products.json?limit=250".$page_info);
if ($response === FALSE)
{
return false;
}
$result_products = $response['body']['products'];
$headers = $response['headers'];
foreach($result_products as $shopify_product){
foreach($shopify_product['variants'] as $variant){
$variant_id = $variant['id'];
$data['variant'] = array(
'id' => $variant['id'],
'inventory_policy' => $inventory_policy,
);
$this->do_put("/admin/api/2021-04/variants/$variant_id.json", $data);
}
}
if(isset($headers['link'])) {
$links = explode(',', $headers['link']);
foreach($links as $link) {
$next_page = false;
if(strpos($link, 'rel="next"')) {
$next_page = $link;
}
}
if($next_page) {
preg_match('~<(.*?)>~', $next_page, $next);
$url_components = parse_url($next[1]);
parse_str($url_components['query'], $params);
$page_info = '&page_info=' . $params['page_info'];
$this->update_inventory_policy_for_all_item($inventory_policy, $page_info);
}
}
return true;
}
I am working with NCBI Blast api. I created logic to get result in xml format but result is comming in html format and this result again going back to redirect to display xml format. when i check original url in browser it shows direct xml data. Can any one give me solutions.
Visit this url you can find my problem peerscientist.net. This is the code.
class BlastAPI{
public function blastdata(){
$url = "https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Put&QUERY=SSWWAHVEMGPPDPILGVTEAYKRDTNSKK&PROGRAM=blastp&FILTER=L&DATABASE=nr&FORMAT_TYPE=XML";
$ncontent = $this->rid($url);
echo '<br/>RID :'.$ncontent.'<br/>';
$geturl = $this->geturl($ncontent);
echo $geturl;
$fulldata = $this->getfullData($geturl);
if($fulldata != ''){
echo '<pre>';
var_dump($fulldata);
echo '</pre>';
}else{
echo "Code Once";
}
}
public function rid($url){
$surl = $url;
echo $surl;
//header('Content-type: text/html');
$content = file_get_contents($surl);
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHtml($content);
libxml_use_internal_errors(false);
$data = $doc->getElementById("rid");
$rid = $data->getAttribute('value');
return $rid;
}
public function geturl($rid){
$srid = $rid;
$mainurl = "https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Get&RID=$srid&FORMAT_TYPE=XML&DESCRIPTIONS=200&ALIGNMENTS=200&NOHEADER=true";
return $mainurl;
}
public function getfullData($url){
$murl = $url;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $murl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$str = curl_exec($curl);
curl_close($curl);
if ($str === FALSE) {
echo "cURL Error: " . curl_error($curl);
}
return $str;
}
}
$nblast = new BlastAPI();
$nblast->blastdata();
I'm quite new to PHP and am creating a web scraper for a project. From this website, https://www.bloglovin.com/en/blogs/1/2/all, I am scraping the blog title, blog url, image url and concatenating a follow through link for later use. As you can see on the page, there are several fields with information for each blogger.
Here is my PHP code so far;
<?php
// Function to make GET request using cURL
function curlGet($url) {
$ch = curl_init(); // Initialising cURL session
// Setting cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$results = curl_exec($ch); // Executing cURL session
curl_close($ch); // Closing cURL session
return $results; // Return the results
}
$blogStats = array();
function returnXPathObject($item) {
$xmlPageDom = new DomDocument();
#$xmlPageDom->loadHTML($item);
$xmlPageXPath = new DOMXPath($xmlPageDom);
return $xmlPageXPath;
}
$blPage = curlGet('https://www.bloglovin.com/en/blogs/1/2/all');
$blPageXpath = returnXPathObject($blPage);
$title = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[1]');
if ($title->length > 0) {
$blogStats['title'] = $title->item(0)->nodeValue;
}
$url = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[2]');
if ($url->length > 0) {
$blogStats['url'] = $url->item(0)->nodeValue;
}
$img = $blPageXpath->query('//*[#id="content"]//div/a/div/#href');
if ($img->length > 0) {
$blogStats['img'] = $img->item(0)->nodeValue;
}
$followLink = $blPageXpath->query('//*[#id="content"]/div[1]/div/a/#href');
if ($followLink->length > 0) {
$blogStats['followLink'] = 'http://www.bloglovin.com' . $followLink->item($i)->nodeValue;
}
print_r($blogStats);
/*$data = $blogStats;
header('Content-Type: application/json');
echo json_encode($data);*/
?>
Currently, this only returns:
Array ( [title] => Fashion Toast [url] => fashiontoast.com [followLink] => http://www.bloglovin.com/blog/4735/fashion-toast )
My question is, what is the best way to loop through each of the results? I've been looking through Stack Overflow and am struggling to find an answer to my question, and my heads going a bit loopy! If anyone could advise me or put me in the right direction, that would be fantastic.
Thank you.
Update:
I'm very sure this is wrong, i'm receiving errors!
<?php
// Function to make GET request using cURL
function curlGet($url) {
$ch = curl_init(); // Initialising cURL session
// Setting cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$results = curl_exec($ch); // Executing cURL session
curl_close($ch); // Closing cURL session
return $results; // Return the results
}
$blogStats = array();
function returnXPathObject($item) {
$xmlPageDom = new DomDocument();
#$xmlPageDom->loadHTML($item);
$xmlPageXPath = new DOMXPath($xmlPageDom);
return $xmlPageXPath;
}
$blogPage = curlGet('https://www.bloglovin.com/en/blogs/1/2/all');
$blogPageXpath = returnXPathObject($blogPage);
$blogger = $blogPageXpath->query('//*[#id="content"]/div/#data-blog-id');
if ($blogger->length > 0) {
$blogStats[] = $blogger->item(0)->nodeValue;
}
foreach($blogger as $id) {
$blPage = curlGet('https://www.bloglovin.com/en/blogs/1/2/all');
$blPageXpath = returnXPathObject($blPage);
$title = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[1]');
if ($title->length > 0) {
$blogStats[$id]['title'] = $title->item(0)->nodeValue;
}
$url = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[2]');
if ($url->length > 0) {
$blogStats[$id]['url'] = $url->item(0)->nodeValue;
}
$img = $blPageXpath->query('//*[#id="content"]//div/a/div/#href');
if ($img->length > 0) {
$blogStats[$id]['img'] = $img->item(0)->nodeValue;
}
$followLink = $blPageXpath->query('//*[#id="content"]/div[1]/div/a/#href');
if ($followLink->length > 0) {
$blogStats[$id]['followLink'] = 'http://www.bloglovin.com' . $followLink->item($i)->nodeValue;
}
}
print_r($blogStats);
/*$data = $blogStats;
header('Content-Type: application/json');
echo json_encode($data);*/ ?>
maybe you want to actually add a dimension to your array. I guess bloggers have a unique id, or somesuch identifier.
moreover, your code seems to execute only once? it might need to be in something like a foreach
I can't do that part for you, but you need an array containing each blogger, or a way to do a while, or for! you have to understand how to iterate over your different bloggers by yourself :)
here an exemple of array of bloggers
[14]['bloggerOne']
[15]['bloggerTwo']
[16]['bloggerThree']
foreach ($blogger as $id => $name)
{
$blPage = curlGet('https://www.bloglovin.com/en/blogs/1/2/' . $name);
// here you have something to do so that $blPage is actually different with each iteration, like changing the url
$blPageXpath = returnXPathObject($blPage);
$title = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[1]');
if ($title->length > 0) {
$blogStats[$id]['title'] = $title->item(0)->nodeValue;
}
$url = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[2]');
if ($url->length > 0) {
$blogStats[$id]['url'] = $url->item(0)->nodeValue;
}
$img = $blPageXpath->query('//*[#id="content"]//div/a/div/#href');
if ($img->length > 0) {
$blogStats[$id]['img'] = $img->item(0)->nodeValue;
}
$followLink = $blPageXpath->query('//*[#id="content"]/div[1]/div/a/#href');
if ($followLink->length > 0) {
$blogStats[$id]['followLink'] = 'http://www.bloglovin.com' . $followLink->item($i)->nodeValue;
}
}
so after the foreach, you array could look like:
['12345']['title'] = whatever
['url'] = url
['img'] = foo
['followLink'] = bar
['4141']['title'] = other
['url'] = urlss
['img'] = foo
['followLink'] = bar
['7415']['title'] = still
['url'] = url4
['img'] = foo
['followLink'] = bar
I recently inherited a RSS/XML parser, and while it seems to work really good, I'm finding some things are missing.
For instance, pulling in a RSS feed from a blog. It's missing all the categories in the items. It shows as each item having only one category when in reality it should show as having a multitude of categories.
Link to Demo: http://dev.o7t.in/rss/
Link to Actual Feed: http://o7thblog.com/feed/
You can see how the first item in the feed itself has 8 total categories in the first item. (may need to view source)
However, in the Demo you can see that it only shows 1 category
Here is my entire code for the class:
<?php
class o7thRssFeedPuller{
public $FeedUrl = ''; // URL of the feed to pull in
public $ReturnJson = false; // Return the array as a JSON encoded string instead?
public $MaxItems = 0; // 0 = unlimited (except by feed), only applicable to GetItems
// Internal holders
private $document;
private $channel;
private $items;
// Get the full RSS feed
public function GetRSS($includeAttributes = false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
return ($this->ReturnJson) ? json_encode($this->document) : $this->document;
}
// Return either an array or a json encoded string
return ($this->ReturnJson) ? json_encode($this->valueReturner()) : $this->valueReturner();
}
// Get the channel data
public function GetChannel($includeAttributes = false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
return ($this->ReturnJson) ? json_encode($this->channel) : $this->channel;
}
// Return either an array or a json encoded string
return ($this->ReturnJson) ? json_encode($this->valueReturner($this->channel)) : $this->valueReturner($this->channel);
}
// Get the items
public function GetItems($includeAttributes=false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
$arr = ($this->MaxItems == 0) ? $this->items : array_slice($this->items, 0, $this->MaxItems);
return ($this->ReturnJson) ? json_encode($arr) : $arr;
}
// Return either an array or a json encoded string
$arr = ($this->MaxItems == 0) ? $this->valueReturner($this->items) : array_slice($this->valueReturner($this->items), 0, $this->MaxItems);
return ($this->ReturnJson) ? json_encode($arr) : $arr;
}
// -------------------------------------------------------------------------------------------------
// Internal Methods
private function loadParser($rss=false) {
if($rss) {
$this->document = array();
$this->channel = array();
$this->items = array();
$DOMDocument = new DOMDocument;
$DOMDocument->strictErrorChecking = false;
$DOMDocument->loadXML($rss);
$this->document = $this->extractDOM($DOMDocument->childNodes);
}
}
private function valueReturner($valueBlock=false) {
if(!$valueBlock) {
$valueBlock = $this->document;
}
foreach($valueBlock as $valueName => $values) {
if(isset($values['value'])) {
$values = $values['value'];
}
if(is_array($values)) {
$valueBlock[$valueName] = $this->valueReturner($values);
} else {
$valueBlock[$valueName] = $values;
}
}
return $valueBlock;
}
private function extractDOM($nodeList,$parentNodeName=false) {
$itemCounter = 0;
foreach($nodeList as $values) {
if(substr($values->nodeName,0,1) != '#') {
if($values->nodeName == 'item') {
$nodeName = $values->nodeName.':'.$itemCounter;
$itemCounter++;
} else {
$nodeName = $values->nodeName;
}
$tempNode[$nodeName] = array();
if($values->attributes) {
for($i=0;$values->attributes->item($i);$i++) {
$tempNode[$nodeName]['properties'][$values->attributes->item($i)->nodeName] = $values->attributes->item($i)->nodeValue;
}
}
if(!$values->firstChild) {
$tempNode[$nodeName]['value'] = $values->textContent;
} else {
$tempNode[$nodeName]['value'] = $this->extractDOM($values->childNodes, $values->nodeName);
}
if(in_array($parentNodeName, array('channel','rdf:RDF'))) {
if($values->nodeName == 'item') {
$this->items[] = $tempNode[$nodeName]['value'];
} elseif(!in_array($values->nodeName, array('rss','channel'))) {
$this->channel[$values->nodeName] = $tempNode[$nodeName];
}
}
} elseif(substr($values->nodeName,1) == 'text') {
$tempValue = trim(preg_replace('/\s\s+/',' ',str_replace("\n",' ', $values->textContent)));
if($tempValue) {
$tempNode = $tempValue;
}
} elseif(substr($values->nodeName,1) == 'cdata-section'){
$tempNode = $values->textContent;
}
}
return (!isset($tempNode)) ? null : $tempNode;
}
// Load in a random header to pass
private function randomContext() {
$headerstrings = array();
$headerstrings['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 5.'.rand(0,2).'; en-US; rv:1.'.rand(2,9).'.'.rand(0,4).'.'.rand(1,9).') Gecko/2007'.rand(10,12).rand(10,30).' Firefox/2.0.'.rand(0,1).'.'.rand(1,9);
$headerstrings['Accept-Charset'] = rand(0,1) ? 'en-gb,en;q=0.'.rand(3,8) : 'en-us,en;q=0.'.rand(3,8);
$headerstrings['Accept-Language'] = 'en-us,en;q=0.'.rand(4,6);
$setHeaders = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'."\r\n".
'Accept-Charset: '.$headerstrings['Accept-Charset']."\r\n".
'Accept-Language: '.$headerstrings['Accept-Language']."\r\n".
'User-Agent: '.$headerstrings['User-Agent']."\r\n";
$contextOptions = array(
'http'=>array(
'method'=>"GET",
'header'=>$setHeaders
)
);
return stream_context_create($contextOptions);
}
}
?>
And for the demo page:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/rss/o7th.rss.feed.puller.php');
$fp = new o7thRssFeedPuller();
$fp->FeedUrl = 'http://o7thblog.com/feed';
$fp->MaxItems = 2;
echo '<table width="100%" cellpadding="0" cellspacing="0">';
echo ' <tr>';
echo ' <td>';
echo ' <textarea cols="120" rows="30">';
print_r($fp->GetItems());
echo ' </textarea>';
echo ' </td>';
echo ' </tr>';
echo '</table>';
?>
So, I assume that the issue lies somewhere in either the valueReturner method or the extractDOM method, but I am just not sure where, nor what I can do to get all the categories in the returned array.
Can you help?
I would suggest using SimpleXML to parse the feed.
Here is how you can do it:
$feed_url = 'http://o7thblog.com/feed/';
$feed = simplexml_load_file($feed_url, null, LIBXML_NOCDATA);
$channel = $feed->channel;
echo "<h1>{$channel->title}</h1>\n";
echo "{$channel->description}\n";
echo "<dl>\n";
foreach ($channel->item as $item) {
echo "<dt>{$item->title}</dt>\n"
. "<dd style=\"margin-bottom: 30px;\"><div style=\"font-size: small;\">{$item->pubDate}</div>\n"
. "<div>{$item->description}</div>\n"
. "Categories: <strong>".implode('</strong>, <strong>', (array) $item->category) . "</strong>\n</dd>";
}
echo "</dl>\n";
Above shows you all categories.
You have written a custom parser for what you can do simply with one line of code!
$feed = (array) simplexml_load_file('http://o7thblog.com/feed/', null, LIBXML_NOCDATA);
I'm using simplexml_load_file to pull album information from the LastFM API and having no problems when the requested album matches.
However, when the album is not found, LastFM returns an error, which causes the code below to output a "failed to open stream" error.
I can see that LastFM is giving me exactly what I need, but am unsure how to proceed. What is the proper way to update the code so that this error/error code is correctly handled?
Code:
$feed = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=".$apikey."&artist=".$artist."&album=".$album."&autocorrect=".$autocorrect);
$albums = $feed->album;
foreach($albums as $album) {
$name = $album->name;
$img = $album->children();
$img_big = $img->image[4];
$img_small = $img->image[2];
$releasedate = $album->releasedate;
$newdate = date("F j, Y", strtotime($releasedate));
if ($img == "") {
$img = $emptyart; }
}
?>
if ($headers[0] == 'HTTP/1.0 400 Bad Request') {
$img_big = $emptyart;
$img_small = $emptyart;
}
That will break with a 403 error ...
Method 1 (not practical):
Basically you can mute the error with # and check if your $feed is empty. In that case, "some error" has happened, either an error with your url or a status failed from last.fm.
$feed = #simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=".$apikey."&artist=".$artist."&album=".$album."&autocorrect=".$autocorrect);
if ($feed)
{
// fetch the album info
}
else
{
echo "No results found.";
}
In both ways, you get no results so you can probably satisfy your needs and showing "No results found" instead of showing him "Last.fm error status code, etc.."
Method 2 (recommended) - Use curl:
function load_file_from_url($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.test.com/');
$str = curl_exec($curl);
if(str === false)
{
echo 'Error loading feed, please try again later.';
}
curl_close($curl);
return $str;
}
function load_xml_from_url($url) {
return #simplexml_load_string(load_file_from_url($url));
}
function getFeed($feedURL)
{
$feed = load_xml_from_url($feedURL);
if ($feed)
{
if ($feed['status'] == "failed")
{
echo "FAIL";
}
else
{
echo "WIN";
}
}
else {echo "Last.fm error";}
}
/* Example:
Album: Heritage
Artist: Opeth
*/
$url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=273f3dc84c2d55501f3dc25a3d61eb39&artist=opeth&album=hwwXCvuiweitage&autocorrect=0";
$feed = getFeed ($url);
// will echo FAIL
$url2 = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=273f3dc84c2d55501f3dc25a3d61eb39&artist=opeth&album=heritage&autocorrect=0";
$feed2 = getFeed ($url2);
// will echo WIN
Wouldn't it be better to first get the url, check if it doesn't contain the error, and then use simplexml_load_string instead?
Working along the lines of evaluating the state of the URL prior to passing it to simplexml_load_file, I tried get_headers, and that, coupled with an if/else statement, seems to have gotten things working.
$url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=".$apikey."&artist=".$artist."&album=".$album."&autocorrect=".$autocorrect;
$headers = get_headers($url, 1);
if ($headers[0] == 'HTTP/1.0 400 Bad Request') {
$img_big = $emptyart;
$img_small = $emptyart;
}
else {
$feed = simplexml_load_file($url);
$albums = $feed->album;
foreach($albums as $album) {
$name = $album->name;
$img = $album->children();
$img_big = $img->image[4];
$img_small = $img->image[2];
$releasedate = $album->releasedate;
$newdate = date("F j, Y", strtotime($releasedate));
if ($img == "") {
$img_big = $emptyart;
$img_small = $emptyart;
}
}
}