I have an array full of sub-arrays, which in turn are full of source names and their website URLs, such as The New York Times and http://newyorktimes.com.
I'm displaying a list of links where the title links to the url and I would like to show the website's favicon in front of each link - a simple idea in theory.
Right now the link list works fine, the code that pulls the favicon is returning its correct URL, and basically everything is working fine, except that it only works for the first link and the page gets messed up thereafter. I finally realized that since the code needs to be run for each url in the foreach loop, there must be some variable conflict going on when the loop runs the second time.
The problem is that my list is dynamically populated (in WordPress) so I never know the number of links in the array, nor what they are, so what I'm wondering is: Is there a way I can dynamically number or otherwise change the variables each time the foreach cycles around so that there aren't multiple instances of the same variables?
Here's the part of my code that's the issue:
echo '<ul class="ll_list">';
foreach ( $ll_entries as $ll_entry ) {
/*----- GET FAVICON -----*/
/* This code needs to run for each url in the array, pull the
favicon, and then the favicon's url needs to be echoed down
below. */
$url = esc_attr( $ll_entry['ll_url'] );
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML(file_get_contents($url));
$xml = simplexml_import_dom($doc);
$arr = $xml->xpath('//link[@rel="shortcut icon"]');
$favicon = $arr[0]['href'];
/*-----------------------*/
echo '<li class="ll_list_item">';
if (file_exists($favicon)) {
echo '<img class="ll_logo_img" src="'.$favicon.'" alt="'. esc_attr( $ll_entry['ll_title'] ).'" /> ';
} else {
echo '<span class="dashicons dashicons-arrow-right"></span> ';
}
echo '<a href="' . esc_attr( $ll_entry['ll_url'] ) . '" title="Visit ' . esc_attr( $ll_entry['ll_title'] ) . ' »" target="_blank">';
echo esc_attr( $ll_entry['ll_title'] );
echo '</a>';
echo '</li>';
}
echo '</ul>';
The correct variable would then also have to be called to the <img>
tag below, which is only echoed if the favicon file exists... so that maybe throws a wrench in the works too?
I've searched around a lot about this and I've found a bit of documentation about "variable variables." I'm not entirely sure how to use them here, but there's nothing in the array that I could use as a variable anyway, unless there's some way to strip the special characters from the url and use that.
Any help would be much appreciated, thank you! If there's an easier way to accomplish my goal I'm all ears.