Streamline this PHP snippet - php

I know this is a Wordpress based question, but I think the answer is definitely more stand-alone PHP.
On almost every site I do for a client I have to add some social media links, which come from an options page. I currently use this kind of snippet;
$twt = of_get_option('twitter');
$fcb = of_get_option('facebook');
$ins = of_get_option('instagram');
if ($twt) {
echo '<li class="twitter">Twitter</li>';
}
if ($fcb) {
echo '<li class="facebook">Facebook</li>';
}
if ($ins) {
echo '<li class="instagram">Instagram</li>';
}
This is fine if there are only a couple of links, but recently one of my main clients seems to be including every social media link under the sun to their designs so doing it this way can be a bit clunky.
Is there a way I can combine everything into a foreach or something?

Identify commonalities:
echo '<li class="twitter">Twitter</li>';
^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^
Identify varying parts:
echo '<li class="twitter">Twitter</li>';
^^^^^^^ ^^^^^^^
Identify dependencies and relationships:
$twt depends on of_get_option(...) whose parameter is the same as the twitter in 2.
The class and the name of the service are dependent on each other. Their relationship is apparently that the name is just the first-letter-uppercased version of the class, but I wouldn't rely on that necessarily.
Unify:
$services = array(
'twitter' => 'Twitter',
'facebook' => 'Facebook'
...
);
foreach ($services as $service => $name) {
if ($url = of_get_option($service)) {
printf('<li class="%s">%s</li>', $service, $url, $name);
// or, if you can't be sure that the variables are safe for HTML interpolation:
// printf('<li class="%s">%s</li>', htmlspecialchars($service), htmlspecialchars($url), htmlspecialchars($name));
}
}

Don't know if you mean exactly that, but check this code:
foreach(array('twitter', 'facebook', 'instagram') as $source)
{
$data = of_get_option($source);
if($data)
{
echo '<li class="'.$source.'">'.ucfirst($source).'</li>';
}
}

You could try something like this:
$social_media = array(
array( 'name' => 'Twitter', 'href' => of_get_option('twitter') ),
array( 'name' => 'Facebook', 'href' => of_get_option('facebook') ),
array( 'name' => 'Instagram', 'href' => of_get_option('instagram') )
);
foreach( $social_media as $s )
echo '<li class="' . strtolower( $s["name"] ) . '">' . $s["name"] . '</li>';
Then simply add the new social media site into the $social_media array.

Try the following:
$social = array('Twitter', 'Facebook', 'Instagram');
for($i=0;$i<length($social); ++$i) {
$twt = of_get_option($social[$i]);
if ($twt) {
echo '<li class="' . strtolower($social[$i]) . '">' . $social[$i]. '</li>';
}
}
You can add additional social networks by adding them to the array. It's a compact solution.

Related

How to pass multiple variables in a href?

I tried some code based on similar questions but keep getting error. Based on this similar question I tried:
$step1 = 'my_shop';
$step2 = 'https://my-website.com/';
echo '<a href="' .$step2. .$step1. '">';
Following the logic from this similar question I also tried:
$step1 = 'my_shop';
$step2 = 'https://my-website.com/';
echo '<a href="' .$step2&$step1. '">';
You should use the http_build_query() function, as it was designed for this:
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
'php' => 'hypertext processor'
);
and then:
$base_url = 'https://my-website.com/';
$query_params = http_build_query($data);
$link = $base_url . '?' . $query_params;
echo 'link text';
Result:
link text

PHP: How to use two dimensional array to display menu?

I think I'm picking this up pretty well, but I'm just stuck on this. I want to display this menu using an array and foreach loop:
<img src="/img/page-icons/credit-card21.png" />Payments
<a target="_blank" href="/cloud"><img src="/img/page-icons/upload123.png" />Cloud</a>
<a target="_blank" href="/portal"><img src="/img/page-icons/earth208.png" />Portal</a>
So to do that I need to turn that into this line in PHP:
echo '<img src="/img/page-icons/' . $image . '" />' . $title . '';
To fill that out in the loop we need to create something like this... which is where I'm stuck:
foreach( $stamp as $link => $target ){
echo '<a href="/' . $link . '" target="' . $target . '">';
foreach( $stamp[] as $title => $image ){
echo '<img src="/img/page-icons/' . $image . '" />' . $title;
}
echo '</a>';
}
I don't really know how to go about the above, just been messing around with it for a while today. I also don't want to always display target="' . $target . '" on every link.
The array would probably be a two dimensional array? Something like this any way:
$stamp = array(
'link' => array('title' => 'image'),
'link' => array('title' => 'image'),
'link' => array('title' => 'image')
);
EDIT:
There's some confusion of what 'target' is, I want to echo 4 values from an array into a link, target is one of the values. I didn't know how to use that in the array so I just left it out.
When you do:
foreach( $stamp as $link => $target )
The $link variable contains the string "link" and the $target variable is an array such as ['title' => 'image'].
What you should probably do is have an array like this:
// Init links
$links = array();
// Add links
$links[] = array(
'title' => 'My Title',
'href' => 'http://www.google.com',
'target' => '_blank',
'image' => 'image.png',
);
foreach ($links as $link)
{
echo '<a href="'.$link['href'].'" target="'.$link['target'].'">';
echo '<img src="/img/page-icons/' . $link['image'] . '" />';
echo $link['title'];
echo '</a>';
}
This is a bit more flexible approach that lets you add other data items to the structure in the future. That $links array could easily be generated in a loop if you have a different data source such as a database as well.
EDIT
To answer your further question, you can prefix the link building with a set of sane defaults like this:
foreach ($links as $link)
{
// Use the ternary operator to specify a default if empty
$href = empty($link['href']) ? '#' : $link['href'];
$target = empty($link['target']) ? '_self' : $link['target'];
$image = empty($link['image']) ? 'no-icon.png' : $link['image'];
$title = empty($link['title']) ? 'Untitled' : $link['title'];
// Write link
echo "<a href='$href' target='$target'>";
echo "<img src='/img/page-icons/$image' />";
echo $title;
echo "</a>";
}
you can set your array like:
$stamp = array(
'0' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target),
'1' => array('title'=>$title, 'image'=>$image,'link'=>$link,,'target'=>$target),
'2' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target)
);
and in foreach you can write
$i=0;
foreach( $stamp as $st=> $target ){
echo '<a href="/' . $st['link'] . '" target="' . $st['target'] . '">';
echo '<img src="/img/page-icons/' . $st['image'] . '" />' . $st['title'];
echo '</a>';
}

PHP Preg_Match array

I want to remove certain characters in a link. i.e.
'http://www.bbc.co.uk', strip everything and just be left with 'bbd'
At the moment i have the following:
$filteredFeed[$item->get_title()] = array('title' => $item->get_title(), 'permalink' => $item->get_permalink(), 'date' => $item->get_date('G:i d-M-y'),
'url' =>$item->get_link());
}
endforeach;
foreach ($filteredFeed as $items) {
echo '<li class="tips"><a href="' . $items['permalink'] . ' "target="_blank"">';
echo $items['title'];
echo '</a>';
echo ' ';
echo '<span class="date">';
echo $items['date'];
echo '</span>';
echo ' ';
//echo $date;
echo '</li>';
'url' =>$item->get_link()); - i get the link here.
How can i strip out the characters?
$url= 'http://www.bbc.co.uk';
$url = basename($url);
$url = str_replace('www.','',$url);
$url = preg_replace('/\.[^\.].*$/','',$url );
But this match always first subdomain exept www. TThen you may have interest to keep the basename.

Creating a HTML list in View from server Controller in PHP

I've got a list of "sites" in an SQL database that I'd like to display on a web page. I need to create a div ID for every site. For the time being I'm doing this (fetch the table into a $_SESSION array, get and display the name of the sites in a loop and do an echo):
<div id='leftnavigation1' class="leftnavigation">
<ul>
<?php
$maxKeys = max(array_keys($_SESSION['usersmeter'])); //check how many sites are in the usersmeter table
for ($i = 0; $i <= $maxKeys; $i++) { //loop every key in the array
$siteName = $_SESSION['usersmeter'][$i]['siteName'];
echo "<li id='siteID$i'><a href='#'><span>" . $siteName . "</span></a></li>"; //display the name of the sites
}
?>
</ul>
</div>
It works well but I think it is a bad practice to include php code into the View.
How else can I do? An AJAX in Javascript ?
Thanks,
Like that you will br try:
<?php
$my_array = array(
'GSU4300' => 'Lili Markina',
'GSU4301' => 'John Kokina',
'GSU4304' => 'Bill Clinong',
'GSU4305' => 'Obamark Chiko'
);
echo '<ul id="somethig">';
foreach ($my_array as $k => $v) {
echo '<li id="' . $k . '">' . $v . '</li>';
}
echo '</ul>';
?>

PHP Read XML Podcast RSS Feed

OK, so, I'm creating a page for a friend's podcast site that lists out all of the episodes to his podcast(s). Essentially, all I'm looking for is how to read the RSS Feed. Parse out the Nodes, and display the information on the screen. (eventually, I'm going to create a player that will play the episodes, but that's much later)
This is how I'm reading the RSS Feed (which is to one of my shows - for testing purposes).
click to see My Feed
<?php
//Errors:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$rss = new DOMDocument();
$rss->load('http://tbpc.podbean.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'guid' => $node->getElementsByTagName('guid')->item(0)->nodeValue,
'enclosure' => $node->getElementsByTagName('enclosure')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 1;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$short = substr($description, 0, strpos( $description, '<'));
$file = $feed[$x]['guid'];
echo '<p><strong>'.$title.'</strong></p>';
echo '<p>'.$description.'</p>';
echo '<p>'.$short.'</p>';
echo '<p>'.$file.'</p>';
}
?>
The problem is - is that I have no idea how to get the information out of the attribute url of the enclosure node so I can display it on the page with the rest of the information (this will come in handy when I make the player - eventually).
SO! How do I get the url attribute from the enclosure node? Am I going about this all wrong?
Any helpful hints would be appreciated. Thanks.
Apologies if you're determined to use DOMDocument() in this, but since nobody has posted an answer so far...here's a script which uses simple_xml_load_file(), which I found quite easy to get to grips with.
<?php
$rss_array = array('http://rss.computerworld.com/computerworld/s/feed/topic/231', 'http://rss.computerworld.com/computerworld/s/feed/topic/230', 'http://rss.computerworld.com/computerworld/s/feed/topic/66', 'http://www.engadget.com/rss.xml', 'http://feeds.webservice.techradar.com/rss/new', 'http://feeds.arstechnica.com/arstechnica/index', 'http://www.notebookcheck.net/News.152.100.html', 'http://electronista.feedsportal.com/c/34342/f/626172/index.rss', 'http://www.anandtech.com/rss/pipeline/', 'http://www.digitimes.com/rss/daily.xml', 'http://feeds.feedburner.com/TechCrunch/', 'http://feeds2.feedburner.com/ziffdavis/pcmag/breakingnews', 'http://feeds.feedburner.com/Liliputing', 'http://feeds.slashgear.com/slashgear', 'http://feeds.feedburner.com/GizmagEmergingTechnologyMagazine', 'http://www.zdnet.com/news/rss.xml', 'http://feeds.feedburner.com/mobilityupdate', 'http://www.techmeme.com/feed.xml', 'http://www.notebookreview.com/rss.xml');
for ($i=0; $i<count($rss_array); $i++ ) {
$rssfeed = simplexml_load_file($rss_array[$i]);
foreach ($rssfeed->channel as $channel) {
echo '<h1>' . htmlentities($channel->title) . '</h1>';
echo '<p>' . htmlentities($channel->description) . '</p>';
echo '<p><a href="' . htmlentities($channel->link) . '">' .
htmlentities($channel->link) . '</a></p>';
echo '<input type="button" value=" >>> " onClick="downloadFileViaAjax(\'' . htmlentities($channel->link) . '\')">';
echo '<ul>';
foreach ($channel->item as $item) {
echo '<li><a href="' . htmlentities($item->link) . '">';
echo htmlentities($item->title) . '</a>';
// echo htmlentities($item->description) . '</li>';
echo '<input type="button" value=" >>> " onClick="downloadFileViaAjax(\'' . htmlentities($item->link) . '\')"></li>';
}
echo '</ul>';
}
}//fur ( $rss_array++ )
?>
Nodes have an getAttribute() method. So you can use:
$node->getElementsByTagName('enclosure')->item(0)->getAttribute('url')
But here is another and more comfortable way to fetch nodes and values from an XML DOM: Use Xpath. See this answer: https://stackoverflow.com/a/20225186/2265374
The $node->getElementsByTagName('enclosure')->item(0) will result in an error if no element is found (same goes for SimpleXML btw). If the node list is cast to string in Xpath, the result is just an empty string and no error is triggered.
You can directly fetch attributes this way, too. Like the url attribute of the enclosure element:
echo 'Enclosure Url: ', $xpath->evaluate('string(enclosure/#url)', $rssItem), "\n";

Categories