w3school example breadcrumb bootstrap php dynamic breadcrumbs

php - example - Breadcrumb dinámico simple



html5 breadcrumb (9)

Aquí hay una gran migaja dinámica simple (ajustar según sea necesario):

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

Creo que este script es de gran interés para cualquier noob por aquí :) incluyéndome a mí :)

Lo que quiero crear es un pequeño código que puedo usar en cualquier archivo y generará una ruta de exploración como esta:

Si el archivo se llama " website.com/templates/index.php ", la ruta de navegación debería mostrar:

Website.com > Templates

^^ enlace ^^ texto plano

Si el archivo se llama " website.com/templates/template_some_name.php ", la ruta de navegación debería mostrar:

Website.com > Templates > Template Some Name

^^ enlace ^^ enlace ^^ texto plano


Comencé con el código de Dominic Barnes, incorporé los comentarios de cWoDeR y aún tenía problemas con las migajas en el tercer nivel cuando usé un subdirectorio. Así que lo reescribí y he incluido el siguiente código.

Tenga en cuenta que he configurado la estructura de mi sitio web de modo que las páginas estén subordinadas (vinculadas desde) una página en el nivel raíz como se establece a continuación:

  • Cree una carpeta con el mismo nombre EXACTO que el archivo (incluida las mayúsculas), menos el sufijo, como una carpeta en el nivel raíz

  • Coloque todos los archivos / páginas subordinados en esta carpeta

(Por ejemplo, si desea eliminar las páginas para Clientes.php:

  • cree una carpeta llamada Customers al mismo nivel que Customers.php

  • agregue un archivo index.php en la carpeta Clientes que redirige a la página de llamada para la carpeta (consulte a continuación el código)

Esta estructura funcionará para múltiples niveles de subcarpetas.

Solo asegúrese de seguir la estructura de archivos descrita anteriormente Y inserte un archivo index.php con el código que se muestra en cada subcarpeta.

El código en la página index.php en cada subcarpeta se ve así:

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

Si usa el directorio raíz del servidor como su raíz web (es decir, / var / www / html), establezca $ root_dir = "": (NO deje la "/" final al final). Si usa un subdirectorio para su sitio web (es decir, / var / www / html / web_root, establezca $ root_dir = "web_root /"; (reemplace web_root con el nombre real de su directorio web) (asegúrese de incluir el final /)

En cualquier caso, aquí está mi código (derivado):

<?php // Big Thank You to the folks on // See http://.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> ?>


Este es el código que yo personalmente uso en mis sitios. Trabaja fuera de la caja.

<?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(); ?>

El 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 }

Siéntase libre de jugar con el relleno y los márgenes de css hasta que lo obtenga para su propio sitio.


Esto puede ser una exageración para una migaja de pan simple, pero vale la pena intentarlo. Recuerdo haber tenido este problema hace mucho tiempo cuando comencé, pero nunca lo resolví realmente. Es decir, hasta que decidí escribir esto ahora. :)

He documentado lo mejor que puedo en línea, en la parte inferior hay 3 posibles casos de uso. ¡Disfrutar! (siéntase libre de hacer cualquier pregunta que pueda tener)

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


Hey Dominic, su respuesta fue buena, pero si tiene un sitio como http://localhost/project/index.php el enlace ''proyecto'' se repite ya que forma parte de $ base y también aparece en la matriz $ path. Así que modifiqué y eliminé el primer elemento de la matriz $ path.

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

No sé si esa es la forma más elegante, pero ahora funciona para mí.

Agrego ese código antes de este en la línea 13 o algo así

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


Hmm, por los ejemplos que dio, parece que "$ _SERVER [''REQUEST_URI'']" y la función explode() podría ayudarlo. Podría usar explotar para dividir la URL que sigue el nombre de dominio en una matriz, separándola en cada barra diagonal.

Como un ejemplo muy básico, algo como esto podría implementarse:

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


También hizo un pequeño script con RDFa (también puede usar microdatos u otros formatos). Compruébelo en google. Este script también tiene en cuenta la estructura de su sitio.

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


Una mejor usando la función explode() es la siguiente ...

No olvide reemplazar su variable de URL en el hipervínculo href .

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


use parse_url y luego parse_url el resultado en un bucle:

$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>''; }

(pseudocódigo)