2010-04-07 89 views
15

我覺得這個劇本大感興趣的任何小白在這裏:)包括我:)簡單的動態痕跡

我想創建一個小的代碼,我可以在任何文件中使用,並會生成一個麪包屑像這樣:

如果文件被稱爲 「website.com/templates/index.php」 麪包屑應顯示:

Website.com > Templates 

  ^^鏈接                                        ^^純文本

如果文件被稱爲 「website.com/templates/template_some_name.php」 麪包屑應顯示:

Website.com > Templates > Template Some Name 

  ^^鏈接                                      ^^鏈接                                ^^純文本

+0

任何人都知道如何在Twig中做到這一點? 在這裏看到我的問題:http://stackoverflow.com/questions/38551401/how-to-create-a-dynamic-breadcrumb-nav-in-twig – user3464091 2016-07-25 07:49:57

回答

23

嗯,從你給它的例子看起來像「$ _SERVER ['REQUEST_URI']」和explode()函數可以幫助你。您可以使用爆炸將域名後面的URL拆分爲數組,並在每個正斜槓處將其分開。

作爲一個非常簡單的例子,像這樣可以實現:

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

感謝您的代碼! – 2010-04-08 10:36:58

3

使用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>'; 
} 

(僞)

+0

感謝您的代碼! – 2010-04-08 10:36:40

39

這可能是一個簡單的麪包屑矯枉過正,但它是值得一試。我記得很久以前我剛開始時遇到這個問題,但我從未真正解決過這個問題。也就是說,直到我決定現在寫這個。 :)

我已經記錄最好的我可以內聯,底部是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> 
+0

感謝您的代碼! – 2010-04-08 10:35:59

+0

沒問題,我希望它可以幫助:) – 2010-04-08 13:53:06

+7

+1有時,所選的答案不適合所有情況。 – dpp 2011-12-27 03:21:02

2

哎多米尼克你的答案是好的,但如果你有一個像http://localhost/project/index.php網站獲得的重複「項目」鏈接,因爲它是$基地的一部分,也出現在$路徑數組。所以我調整並刪除了$ 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)); 
6

也做了使用RDFa(你也可以使用微資料或其他格式)Check it out on google 這個腳本也保持牢記您的網站的一個小腳本之前添加代碼結構體。

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;} 
3

我開始與多米尼克·巴恩斯的代碼,從cWoDeR納入反饋,我仍然不得不用麪包屑問題在第三級的時候我用了一個子目錄。所以我重寫了它,並且包含了下面的代碼。

請注意,我已經設置了我的網站結構,使得頁面從屬於(從鏈接)一個在根目錄一級頁面被設置如下:

  • 與精確創建一個文件夾同名的文件(包括大小寫),減去後綴,作爲文件夾在根級別

  • 地方下屬的所有文件/頁面到這個文件夾

(例如,如果想爲Customers.php sobordinate頁:

  • 創建一個在同一水平Customers.php

  • 稱爲客戶文件夾中添加一個index.php文件將被重定向客戶文件夾到該文件夾​​的主叫頁面(請參閱下面的代碼)

此結構將適用於多個級別的子文件夾。

只要確保你遵循上述文件結構,並插入一個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目錄的實際名稱替換web_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> 
?> 
2

這裏是一個偉大簡單的動態痕跡(根據需要調整):

<?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>'; 
?> 
0

一個更好的使用explode()功能如下...

不要忘記在超鏈接href中替換您的URL變量。

<?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 .= '/'; 
     } 
    } 
?>