【问题标题】:Simple dynamic breadcrumb简单的动态面包屑
【发布时间】:2011-02-05 08:34:44
【问题描述】:

我认为这个脚本对这里的任何菜鸟都很感兴趣 :) 包括我 :)

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

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

Website.com > Templates

 ^^ 链接                    ^^纯文本

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

Website.com > Templates > Template Some Name

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

【问题讨论】:

标签: php dynamic breadcrumbs


【解决方案1】:

这对于简单的面包屑来说可能有点过头了,但值得一试。我记得很久以前我刚开始的时候就有这个问题,但我从来没有真正解决过。也就是说,直到我现在才决定写这个。 :)

我已尽我所能内联记录,底部是 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>

【讨论】:

  • 没问题,希望对你有帮助:)
  • 另外,不是每个人都使用短标签&lt;? ?&gt; :)
  • 不确定是谁抄袭了谁。刚找到this
  • 哈哈,太棒了。我绝对是自己写的,但我根本不介意它变成复制面。 :)
  • @NahserBakht 通过将$base = ($_SERVER['HTTPS'] //code 更改为$base = (isset($_SERVER['HTTPS']) 来消除警告,然后将`$last = end(array_keys($path));` 更改为$pathkeys = array_keys($path); $last = end($pathkeys); 希望有帮助!
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    还用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;}
    

    【讨论】:

      【解决方案4】:

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

      (伪代码)

      【讨论】:

        【解决方案5】:

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

        请注意,我已经设置了我的网站结构,以便从属于(链接自)根级别页面的页面设置如下:

        • 创建一个与文件同名的文件夹(包括大写),减去后缀,作为根级别的文件夹

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

        (例如,如果想要为 Customers.php 提供更高级的页面:

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

        • 将 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_root 替换为您的 Web 目录的实际名称)(确保包含尾随 /)

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

        <?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>
        ?>
        

        【讨论】:

          【解决方案6】:

          嘿,dominic,你的回答很好,但如果你有一个像http://localhost/project/index.php 这样的网站,'project' 链接会重复,因为它是 $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));
          

          【讨论】:

            【解决方案7】:

            这是一个很棒的简单动态面包屑(根据需要进行调整):

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

            【讨论】:

              【解决方案8】:

              一个更好的使用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 .= '/';
                       }
                   }
              ?>
              

              【讨论】:

                【解决方案9】:

                这是我基于 Skeptic 回答的解决方案。它从 WordPress DB 获取页面标题,而不是从 URL 获取,因为拉丁字符存在问题(slug 没有拉丁字符)。您也可以选择是否显示“主页”项目。

                /**
                 * Show Breadcrumbs
                 * 
                 * @param string|bool $home
                 * @param string $class
                 * @return string
                 * 
                 * Using: echo breadcrumbs();
                 */
                function breadcrumbs($home = 'Home', $class = 'items') {
                    $breadcrumb  = '<ul class="'. $class .'">';
                    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
                
                    if ($home) {
                        $breadcrumb .= '<li><a href="' . get_site_url() . '">' . $home . '</a></li>';
                    }
                
                    $path = '';
                    foreach ($breadcrumbs as $crumb) {
                        $path .=  $crumb . '/';
                        $page = get_page_by_path($path);
                
                        if ($home && ($page->ID == get_option('page_on_front'))) {
                            continue;
                        }
                
                        $breadcrumb .= '<li><a href="'. get_permalink($page) .'">' . $page->post_title . '</a></li>';
                    }
                
                    $breadcrumb .= '</ul>';
                    return $breadcrumb;
                }
                

                使用:

                <div class="breadcrumb">
                    <div class="container">
                        <h3 class="breadcrumb__title">Jazda na maxa!</h3>
                        <?php echo breadcrumbs('Start', 'breadcrumb__items'); ?>
                    </div>
                </div>
                

                【讨论】:

                  【解决方案10】:

                  这是我个人在我的网站中使用的代码。开箱即用。

                  <?php
                  function breadcrumbs($home = 'Home') {
                    global $page_title; //global varable that takes it's value from the page that breadcrubs will appear on. Can be deleted if you wish, but if you delete it, delete also the title tage inside the <li> tag inside the foreach loop.
                      $breadcrumb  = '<div class="breadcrumb-container"><div class="container"><ol class="breadcrumb">';
                      $root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
                      $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
                      $breadcrumb .= '<li><i class="fa fa-home"></i><a href="' . $root_domain . '" title="Home Page"><span>' . $home . '</span></a></li>';
                      foreach ($breadcrumbs as $crumb) {
                          $link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
                          $root_domain .=  $crumb . '/';
                          $breadcrumb .= '<li><a href="'. $root_domain .'" title="'.$page_title.'"><span>' . $link . '</span></a></li>';
                      }
                      $breadcrumb .= '</ol>';
                      $breadcrumb .= '</div>';
                      $breadcrumb .= '</div>';
                      return $breadcrumb;
                  }
                  echo breadcrumbs();
                  ?>
                  

                  CSS:

                  .breadcrumb-container {
                      width: 100%;
                      background-color: #f8f8f8;
                      border-bottom-color: 1px solid #f4f4f4;
                      list-style: none;
                      margin-top: 72px;
                      min-height: 25px;
                      box-shadow: 0 3px 0 rgba(60, 57, 57, .2)
                  }
                  
                  .breadcrumb-container li {
                      display: inline
                  }
                  .breadcrumb {
                      font-size: 12px;
                      padding-top: 3px
                  }
                  .breadcrumb>li:last-child:after {
                      content: none
                  }
                  
                  .breadcrumb>li:last-child {
                      font-weight: 700;
                      font-style: italic
                  }
                  .breadcrumb>li>i {
                      margin-right: 3px
                  }
                  
                  .breadcrumb>li:after {
                      font-family: FontAwesome;
                      content: "\f101";
                      font-size: 11px;
                      margin-left: 3px;
                      margin-right: 3px
                  }
                  .breadcrumb>li+li:before {
                      font-size: 11px;
                      padding-left: 3px
                  }
                  

                  随意使用 css 填充和边距,直到找到适合自己网站的内容。

                  【讨论】:

                    【解决方案11】:
                    function  makeBreadCrumbs($separator = '/'){
                            //extract uri path parts into an array
                            $breadcrumbs =  array_filter(explode('/',parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
                    
                            //determine the base url or domain 
                            $base = (isset($_SERVER['HTTPS'])  ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
                    
                            $last  =  end($breadcrumbs); //obtain the last piece of the path parts
                            $crumbs['Home'] = $base; //Our first crumb is the base url 
                            $current =  $crumbs['Home']; //set the current breadcrumb to base url
                    
                        //create valid urls from the breadcrumbs and store them in an array
                        foreach ($breadcrumbs as $key => $piece) {
                    
                        //ignore file names and create urls from  directory path
                        if( strstr($last,'.php') == false){
                            $current   =  $current.$separator.$piece;
                            $crumbs[$piece] =$current;
                    
                        }else{
                    
                            if($piece !== $last){
                                $current   =  $current.$separator.$piece;
                                $crumbs[$piece] =$current;
                            }
                        }
                    
                        }
                    
                    
                        $links = '';
                        $count = 0;
                    
                    //create html tags for displaying the breadcrumbs
                    foreach ($crumbs as $key => $value) :
                        $x = array_filter(explode('/',parse_url($value, PHP_URL_PATH)));
                        $last =  end($x);
                        //this will add a class to the last link to control its appearance
                        $clas = ($count === count($crumbs) -1 ? ' current-crumb' : '' );
                    
                        //determine where to print separators 
                        $sep = ( $count > -1 && $count < count($crumbs) -1 ? '&raquo;' :'');
                    
                        $links .= "<a class=\"$clas\" href=\"$value\">$key</a> $sep";
                        $count++;
                    
                    endforeach;
                    
                    return $links; 
                    

                    }

                    【讨论】:

                    • 这就是我在 PHP 中制作自己的面包屑的方式,更多代码示例你可以试试codeparl.com
                    • 希望它能解决问题,但请添加对代码的解释,以便用户完全理解他/她真正想要的。
                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2018-01-28
                    • 2022-01-21
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多