简单的dynamic面包屑

我认为这个剧本对这里的任何小老师都很有帮助:)包括我:)

我想创build的是一个可以在任何文件中使用的小代码,并将生成一个面包屑如下所示:

如果该文件被称为“ website.com/templates/index.php ”,则面包屑应显示:

Website.com > Templates 

^^链接^^纯文本

如果该文件被称为“ website.com/templates/template_some_name.php ”,则面包屑应显示:

 Website.com > Templates > Template Some Name 

^^链接^^链接^^纯文本

8 Solutions collect form web for “简单的dynamic面包屑”

嗯,从你给的例子看起来像“$ _SERVER ['REQUEST_URI']”和explode()函数可以帮助你。 您可以使用爆炸将域名后面的URL拆分成一个数组,并在每个正斜杠处将其分开。

作为一个非常基本的例子,可以实现这样的事情:

 $crumbs = explode("/",$_SERVER["REQUEST_URI"]); foreach($crumbs as $crumb){ echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' '); } 

这可能是一个简单的面包屑矫枉过正,但它是值得一试。 我记得很久以前有这个问题,但是我从来没有真正解决过这个问题。 也就是说,直到我决定现在写这个。 🙂

我已经logging了最好的我可以内联,底部是3个可能的用例。 请享用! (随时提出您可能有任何问题)

 <?php // This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path function breadcrumbs($separator = ' &raquo; ', $home = 'Home') { // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))); // This will build our "base URL" ... Also accounts for HTTPS :) $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'; // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL) $breadcrumbs = Array("<a href=\"$base\">$home</a>"); // Find out the index for the last value in our path array $last = end(array_keys($path)); // Build the rest of the breadcrumbs foreach ($path AS $x => $crumb) { // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space) $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb)); // If we are not on the last index, then display an <a> tag if ($x != $last) $breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>"; // Otherwise, just display the title (minus) else $breadcrumbs[] = $title; } // Build our temporary array (pieces of bread) into one big string :) return implode($separator, $breadcrumbs); } ?> <p><?= breadcrumbs() ?></p> <p><?= breadcrumbs(' > ') ?></p> <p><?= breadcrumbs(' ^^ ', 'Index') ?></p> 

也做了一个小脚本使用RDFa(你也可以使用微数据或其他格式) 检查它在谷歌这个脚本也记住你的网站结构。

 function breadcrumbs($text = 'You are here: ', $sep = ' &raquo; ', $home = 'Home') { //Use RDFa breadcrumb, can also be used for microformats etc. $bc = '<div xmlns:v="http://rdf.data-vocabulary.org/#" id="crums">'.$text; //Get the website: $site = 'http://'.$_SERVER['HTTP_HOST']; //Get all vars en skip the empty ones $crumbs = array_filter( explode("/",$_SERVER["REQUEST_URI"]) ); //Create the home breadcrumb $bc .= '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$home.'</a>'.$sep.'</span>'; //Count all not empty breadcrumbs $nm = count($crumbs); $i = 1; //Loop the crumbs foreach($crumbs as $crumb){ //Make the link look nice $link = ucfirst( str_replace( array(".php","-","_"), array(""," "," ") ,$crumb) ); //Loose the last seperator $sep = $i==$nm?'':$sep; //Add crumbs to the root $site .= '/'.$crumb; //Make the next crumb $bc .= '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$link.'</a>'.$sep.'</span>'; $i++; } $bc .= '</div>'; //Return the result return $bc;} 

使用parse_url ,然后在循环中输出结果:

 $urlinfo = parse_url($the_url); echo makelink($urlinfo['hostname']); foreach($breadcrumb in $urlinfo['path']) { echo makelink($breadcrumb); } function makelink($str) { return '<a href="'.urlencode($str).'" title="'.htmlspecialchars($str).'">'.htmlspecialchars($str).'</a>'; } 

(伪代码)

我从Dominic Barnes的代码开始,join了来自cWoDeR的反馈,当我使用子目录时,我仍然遇到了第三级的面包屑问题。 所以我重写了它,并包含下面的代码。

请注意,我已经build立了我的网站结构,使得从根级链接到(从链接)页面的页面设置如下:

  • 创build与文件具有相同名称的文件夹(包括大写字母),减去后缀作为根级别的文件夹

  • 将所有从属文件/页面放入此文件夹

(例如,如果想为Customers.php索引页面:

  • 在与Customers.php相同的级别创build一个名为Customers的文件夹

  • 将一个index.php文件添加到Customers文件夹中,该文件夹redirect到该文件夹​​的调用页面(请参阅下面的代码)

这个结构将适用于多个级别的子文件夹。

只要确保你遵循上述的文件结构,并插入一个index.php文件与每个子文件夹中显示的代码。

每个子文件夹的index.php页面中的代码如下所示:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Redirected</title> </head> <body> <?php $root_dir = "web_root/" ; $last_dir=array_slice(array_filter(explode('/',$_SERVER['PHP_SELF'])),-2,1,false) ; $path_to_redirect = "/".$root_dir.$last_dir[0].".php" ; header('Location: '.$path_to_redirect) ; ?> </body> </html> 

如果你使用服务器的根目录作为你的web根目录(例如/ var / www / html),那么设置$ root_dir =“”:(不要在后面留下“/”)。 如果你为你的网站使用了一个子目录(例如/ var / www / html / web_root,那么设置$ root_dir =“web_root /”;(用你web目录的实际名称replaceweb_root)(确保包含尾部/

无论如何,这里是我的(衍生)代码:

 <?php // Big Thank You to the folks on StackOverflow // See http://stackoverflow.com/questions/2594211/php-simple-dynamic-breadcrumb // Edited to enable using subdirectories to /var/www/html as root // eg, using /var/www/html/<this folder> as the root directory for this web site // To enable this, enter the name of the subdirectory being used as web root // in the $directory2 variable below // Make sure to include the trailing "/" at the end of the directory name // eg use $directory2="this_folder/" ; // do NOT use $directory2="this_folder" ; // If you actually ARE using /var/www/html as the root directory, // just set $directory2 = "" (blank) // with NO trailing "/" // This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path function breadcrumbs($separator = ' &raquo; ' , $home = 'Home') { // This sets the subdirectory as web_root (If you want to use a subdirectory) // If you do not use a web_root subdirectory, set $directory2=""; (NO trailing /) $directory2 = "web_root/" ; // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ; $path_array = array_filter(explode('/',$path)) ; // This line of code accommodates using a subfolder (/var/www/html/<this folder>) as root // This removes the first item in the array path so it doesn't repeat if ($directory2 != "") { array_shift($path_array) ; } // This will build our "base URL" ... Also accounts for HTTPS :) $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'. $directory2 ; // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL) $breadcrumbs = Array("<a href=\"$base\">$home</a>") ; // Get the index for the last value in our path array $last = end($path_array) ; // Initialize the counter $crumb_counter = 2 ; // Build the rest of the breadcrumbs foreach ($path_array as $crumb) { // Our "title" is the text that will be displayed representing the filename without the .suffix // If there is no "." in the crumb, it is a directory if (strpos($crumb,".") == false) { $title = $crumb ; } else { $title = substr($crumb,0,strpos($crumb,".")) ; } // If we are not on the last index, then create a hyperlink if ($crumb != $last) { $calling_page_array = array_slice(array_values(array_filter(explode('/',$path))),0,$crumb_counter,false) ; $calling_page_path = "/".implode('/',$calling_page_array).".php" ; $breadcrumbs[] = "<a href=".$calling_page_path.">".$title."</a>" ; } // Otherwise, just display the title else { $breadcrumbs[] = $title ; } $crumb_counter = $crumb_counter + 1 ; } // Build our temporary array (pieces of bread) into one big string :) return implode($separator, $breadcrumbs) ; } // <p><?= breadcrumbs() ? ></p> // <p><?= breadcrumbs(' > ') ? ></p> // <p><?= breadcrumbs(' ^^ ', 'Index') ? ></p> ?> 

嘿多米尼克你的答案是好的,但如果你有一个网站像http://localhost/project/index.php '项目'链接重复,因为它是$ base的一部分,也出现在$path数组。 所以我调整并删除了$ path数组中的第一个项目。

 //Trying to remove the first item in the array path so it doesn't repeat array_shift($path); 

我不知道这是否是最优雅的方式,但它现在对我有用。

我在第13行之前添加这个代码

 // Find out the index for the last value in our path array $last = end(array_keys($path)); 

这是一个非常简单的dynamicbreadcrumb(根据需要调整):

  <?php $docroot = "/zen/index5.php"; $path =($_SERVER['REQUEST_URI']); $names = explode("/", $path); $trimnames = array_slice($names, 1, -1); $length = count($trimnames)-1; $fixme = array(".php","-","myname"); $fixes = array(""," ","My<strong>Name</strong>"); echo '<div id="breadwrap"><ol id="breadcrumb">'; $url = ""; for ($i = 0; $i <= $length;$i++){ $url .= $trimnames[$i]."/"; if($i>0 && $i!=$length){ echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>'; } elseif ($i == $length){ echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>'; } else{ echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span>&nbsp;</span></a></li>'; } } echo '</ol>'; ?> 

使用explode()函数的更好的方法如下…

不要忘记在超链接hrefreplace你的URLvariables。

 <?php if($url != ''){ $b = ''; $links = explode('/',rtrim($url,'/')); foreach($links as $l){ $b .= $l; if($url == $b){ echo $l; }else{ echo "<a href='URL?url=".$b."'>".$l."/</a>"; } $b .= '/'; } } ?> 
  • PHP生成文件下载然后重定向
  • 返回数组中最高值的索引
  • 在PHP中简短的唯一ID
  • 如何使用WHERE IN与Doctrine 2
  • CasperJS将数据传回给PHP
  • 在MySQL“IN”子句中用逗号分隔值
  • 从PHP中的平面数组构build一棵树
  • 如何从offline_access弃用以来扩展访问令牌的有效性
  • 通过API获取Google PageRank(PHP)
  • 什么是对象的var_dump中的对象(someClass)旁边的#<some-number>? 我有一个推论。 我对吗?
  • 防止直接访问由ajax函数调用的文件