Making A List Of Links With PHP - php

I would like to know how to make a list of links appear on my page displaying a name but when you click it, it navigates to the link.
I currently know how to make a list and display the items of it using the foreach command and arrays but is there a way I can make it so I have an array, containing an array, containing the name of the link and the link itself, like so:
$links = array(array("Google","//google.co.uk"),array("Bing","//bing.co.uk"))
foreach ($links as $myurl){
foreach ($myurl as $url){
echo "<a href='".$url."'>".$myurl."</a>";
}};
I know the above doesn't work but if anyone can help with this problem, it is much appreciated.

$links = array('Google' => 'www.google.com', 'Yahoo' => 'www.yahoo.com');
foreach($links as $k => $v) {
echo '' . $v . '';
}
As you can see I don't specify http or https, just // works on both! See: http://google-styleguide.googlecode.com/svn/trunk/htmlcssguide.xml
You can add links to $links with:
$links['stackoverflow'] = 'www.stackoverflow.com';

$links = array(
array("Google","//google.co.uk"),
array("Bing","//bing.co.uk")
);
foreach ($links as $urlitem){
echo "<a href='".$urlitem[1]."'>".$urlitem[0]."</a>";
}

Related

Different Array Values depending on the if statement

I am building a web crawler which scans links, titles and meta descriptions from links that are found from one url submitted
This if statement i think is correct. $description is the variable which holds all the descriptions from the array $link. But i notice not all sites have a meta description (wikipedia for example) so i have decided that i would like the first twenty characters to act as the description if the description is empty. (By the way, the function and calling of everything works, i just wanted you to see it)
if ($description == '') {
$html = file_get_contents($link);
preg_match('%(<p[^>]*>.*?</p>)%i', $html, $re);
$res = get_custom_excerpt($re[1]);
echo "\n";
echo $res;
echo "\n";
}
However, in the array, the links are stored in [link], the title of the link in [title] and the description in [description]. But i don't know how i would cope with adding $res to my array and to only use if the if statement works.
$output = Array();
foreach ($links as $thisLink) {
$output[] = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink), getMetas($res));
}
print_r($output);
You can use array_push() to add $res back to your array and then evaluate the array however you need to; not 100% sure what you're trying to do...
From your wording I think you want to do this:
$outputs = array();
foreach ($links as $thisLink) {
$output = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink));
if ($output['description'] == null) {
$output['description'] = getMetas($res);
}
$outputs[] = $output;
}
You might want to adjust the if statement because I do not know what getMetas() returns when there is not description.

url_to_absolute query

right, i am building a web crawler and there is a section of my code which translates to absolute urls instead of /macbookpro/ to http://www.apple.com/macbookpro. but when i echo my code, it only prints one result, which is the first link it sees why. Do i have to create an array, because when i did, i echoed the array and listed was the word 'Array'
<?php
require_once('simplehtmldom_1_5/simple_html_dom.php');
require_once('url_to_absolute/url_to_absolute.php');
$URL = 'http://www.theqlick.com'; // change it for urls to grab
// grabs the urls from URL
$file = file_get_html($URL);
foreach ($file->find('a') as $theelement) {
$links = url_to_absolute($URL, $theelement->href);
}
echo $links;
?>
var_dump your array, it gives you a text representation of your objects. It will show you the array and it's elements. Echo is more for just outputting strings. you could loop your array and echo each element, but if you just want to see it, var_dump is the answer.
http://www.php.net/manual/en/function.var-dump.php
If you are trying to build an array in $links You need to do
$links[] = url_to_absolute($URL, $theelement->href);
Right now, you are overriding the value of $links with each loop iteration.
You should also decalre $links = array(); somewhere before your foreach loop.
<?php
require_once('simplehtmldom_1_5/simple_html_dom.php');
require_once('url_to_absolute/url_to_absolute.php');
$links = Array();
$URL = 'http://www.theqlick.com'; // change it for urls to grab
// grabs the urls from URL
$file = file_get_html($URL);
foreach ($file->find('a') as $theelement) {
$links[] = url_to_absolute($URL, $theelement->href);
}
print_r($links);
So you'll need to init the array, add to it with [] and finally use something suitable to actually print it out, such as print_r.

how to make an anchor url via foreach using grabbed URL n TITLE

I use preg_match_all to grab urls and titles from another page and grabbing is ok but i cant get them in to one using foreach! or is there another way instead of foreach?
//gets URLs of href='xxxx'
preg_match_all('/a href="([^"]+)" class=l.+?>.+?<\/a>/',$sear,$results);
//gets titles of >xxxx</a>
preg_match_all('/a href=".+?" class=l.+?>([^"]+)<\/a>/',$sear,$t);
Below code Displays grabbed URLs
foreach ($results[1] as $url)
{
echo "<a href='$url'>$u</a> <br>";
$i++;
}
Below code Displays grabbed titles
foreach ($t[1] as $title)
{
echo $title;
$i++;
}
but i dont know how to display them(url & title) in one foreach so i can make it like
<a href='URL'>Title</a>
I'm new to php please help me!!
you could use normal for cycle:
if ( count($result[1]) == count($t[1]) ){
for ( $i = 0; $i < count($result[1]); $i++ ){
echo "<a href='" . $result[1][$i] . "'>" . $t[1][$i] . "</a> <br>";
}
}
Now this should only be used if both number of URL's and titles is matches. You should also consider matching both URL and title in the same preg_match_all and that way you won't need to access two array but single one... (as Brian Warshaw suggested)
Match them both in one expression using the PREG_SET_ORDER flag:
preg_match_all('/a href="([^"]+)" class=l.+?>(.+?)<\/a>/',$sear,$results, PREG_SET_ORDER);
Then you'll have two matched groups in your results array. Each element will contain an array of each match set (the manual explains this well for that flag), and you can loop through the $results array and then get each group from within.
How about matching both the URL and the link display text at once:
preg_match_all('/a href="([^"]+)" class=l.+?>([^"]+)<\/a>/',$sear,$results);
Your $results array should now contain both matched values, in the [1] and [2] indices:
foreach ($results as $link) {
$url = $link[1];
$text = $link[2];
echo "Link '$text' to $url";
}

Creating an array via foreach

I'm using SimpleXML to extract images from a public feed # Flickr. I want to put all pulled images into an array, which I've done:
$images = array();
foreach($channel->item as $item){
$url = $path->to->url;
$images[] = $url;
}
From this I can then echo out all the images using:
foreach($images as $image){
//output image
}
I then decided I wanted to have the image title as well as the user so I assumed I would use:
$images = array();
foreach($channel->item as $item){
$url = $path->to->url;
$title = $path->to->title;
$images[$title] = $url;
}
I thought this would mean by using $image['name of title'] I could output the URL for that title, but it gives an Illegal Offset Error when I run this.. and would only have the title and url, but not the user.
After Googling a bit I read you cannot use _ in the array key, but I tried using:
$normal = 'dddd';
$illegal = ' de___eee';
$li[$normal] = 'Normal';
$li[$illegal] = 'Illegal';
And this outputs right, ruling out _ is illegal in array keys (..I think).
So now I'm really confused why it won't run, when I've used print_r() when playing around I've noticed some SimpleXML objects in the array, which is why I assume this is giving an error.
The ideal output would be an array in the format:
$image = array( 0 => array('title'=>'title of image',
'user'=>'name of user',
'url' =>'url of image'),
1 => array(....)
);
But I'm really stumped how I'd form this from a foreach loop, links to reference as well as other questions (couldn't find any) are welcome.
$images = array();
foreach ($channel->item as $item){
$images[] = array(
'title' => $item->path->to->title,
'url' => $item->path->to->url
);
}
foreach ($images as $image) {
echo "Title: $image[title], URL: $image[url]\n";
}
Underscore is not forbidden symbol for array keys, the only problem you might run to, that titles some times overlap and you might loose some items in your array. Most correct way would be deceze example
If you prefer associative array you can use image path as array key and title as value.

Foreach and 2D Array in PHP

$mainMenu['Home'][1] = '/mult/index.php';
$mainMenu['Map'][1] = '/mult/kar.php';
$mainMenu['MapA'][2] = '/mult/kara.php';
$mainMenu['MapB'][2] = '/mult/karb.php';
$mainMenu['Contact'][1] = '/mult/sni.php';
$mainMenu['Bla'][1] = '/mult/vid.php';
This is a menu, 1 indicates the main part, 2 indicates the sub-menu. Like:
Home
Map
-MapA
-MapB
Contat
Bla
I know how to use foreach but as far as I see it is used in 1 dimensional arrays. What I have to do in the example above?
You would need to nest two foreach BUT, there is nothing about your data structure that easily indicates what is a sub-item. Map vs. MapA? I guess a human could figure that out, but you'll have to write a lot of boilerlate for your script to sort that.. Consider restructuring your data so that it more closely matches what you are trying to achieve.
Here's an example. You can probably come up with a better system, though:
$mainMenu = array(
'Home' => '/mult/index.php',
'Map' => array(
'/mult/kar.php',
array(
'MapA' => '/mult/kara.php',
'MapB' => '/mult/karb.php'
)
),
'Contact' => '/mult/sni.php',
...
);
You nest foreach statements; Something like this should do the work.
foreach($mainMenu as $key=>$val){
foreach($val as $k=>$v){
if($k == 2){
echo '-' . $key;
}else{
echo $key;
}
}
}
Foreach can just as easily be used in multi-dimensional arrays, the same way you would use a for loop.
Regardless, your approach is a little off, here's a better (but still not great) solution:
$mainMenu['Home'][1] = '/mult/index.php';
$mainMenu['Map'][1] = '/mult/kar.php';
$mainMenu['Map']['children']['MapA'] = '/mult/kara.php';
$mainMenu['Map']['children']['MapB'] = '/mult/karb.php';
$mainMenu['Contact'][1] = '/mult/sni.php';
$mainMenu['Bla'][1] = '/mult/vid.php';
foreach($mainMenu as $k => $v){
// echo menu item
if(isset($v['children'])){
foreach($v['children'] as $kk => $vv){
// echo submenu
}
}
}
That said, this only does 1-level of submenus. Either way, it should help you get the idea!

Categories