Creating an image gallery without MySQL
Ever wanted to create a photo gallery that would fetch the photos from a folder on the server without actually taking the image paths from a database?
Well, here's a small code snippet that would solve the problem for you and output the paths to the images into an XML with the following structure:
Well, here's a small code snippet that would solve the problem for you and output the paths to the images into an XML with the following structure:
CODE:
<?xml version="1.0" encoding="utf-8"?>
<gallery>
<item iPath="path/to/file1.jpg"/>
<item iPath="path/to/file2.jpg"/>
</gallery>
If you have any questions regarding it, or encounter any issues implementing it in your own project, drop a comment, I'll help you as I can.
CODE:
<?php
header("content-type:text/xml;charset=utf-8");
function getDirTree($dir,$p=true) {
if (!is_dir($dir)) return false;
$d = dir($dir);
$x=array();
while (false !== ($r = $d->read())) {
if($r != "." && $r != ".." && (($p == false &&is_dir($dir.$r)) || $p == true)) {
$x[$r] = (is_dir($dir.$r) ? array() :(is_file($dir.$r) ? true : false));
}
}
foreach ($x as $key => $value) {
if (is_dir($dir.$key."/")) {
$x[$key] = getDirTree($dir.$key."/", $p);
}
}
ksort($x);
return $x;
}
function parse($dir) {
$tree = getDirTree($dir, true);
if ($tree) {
foreach ($tree as $k=>$v) {
if (is_array($v)) {
foreach ($v as $key=>$val) {
if (!is_array($key)) {
if (substr($key,-4)==='.jpg') {
echo '<item iPath="'.$key.'"/>';
}
else {
if (is_array($val)) {
parse($dir.$k."/");
}
}
}
}
}
}
}
return false;
}
echo '<?xml version="1.0" encoding="utf-8"?>
<gallery>';
parse('repository/');
echo '</gallery>';
?>
The code might still contain some "artifacts" from tests and such, please delete them if you spot them, the code works regardless so don't worry. Publishing date: 15-04-2011 Claudiu Gilcescu-Ceia
Niciun comentariu:
Trimiteți un comentariu