I am currently using SimpleXML to reading an xml file to generate my first array. This array displays a list of images that are found in a directory and written to xml file.
This has worked for me in the past until I upload new photos to the same album. I like to know what one does to get a complete list of images that got uploaded to the end of that first array. Any suggestions?
XML File:
<album>
<image path="/albums/1/images/100_4124.jpg" />
<image path="/albums/1/images/100_4307.jpg" />
<image path="/albums/1/images/100_4335.jpg" />
</album>
SimpleXML to get array:
$xml = simplexml_load_file('/albums/1/photos.xml');
foreach ($xml->image as $image) {
echo '<li><img src="'.$image.'"></li>';
}
What I am getting for my results:
<li><img src="/albums/1/images/100_4124.jpg"></li>
<li><img src="/albums/1/images/100_4307.jpg"></li>
<li><img src="/albums/1/images/100_4335.jpg"></li>
Scanning the directory for all images:
if ($handle = #opendir('/albums/1/')) {
$filenames = array();
while (false !== ($file = readdir($handle))) {
$ext = substr($file, strrpos($file, '.') + 1);
if ($file != '.' && $file != '..') {
$filenames[] = $file;
$total++;
}
}
}
closedir($handle);
foreach ($filenames as $filename) {
echo '<li><img src="'.$filename.'"></li>';
}
What I would like to get for results using both arrays:
<li><img src="/albums/1/images/100_4124.jpg"></li>
<li><img src="/albums/1/images/100_4307.jpg"></li>
<li><img src="/albums/1/images/100_4335.jpg"></li>
<li><img src="/albums/1/images/100_9000.jpg"></li>
<li><img src="/albums/1/images/100_9001.jpg"></li>
<li><img src="/albums/1/images/100_9002.jpg"></li>
The last 3 images that are missing from xml file would be added it to the end of the list.
Perhaps this would work for you?
<?php
$images = array();
foreach ($xml->image as $image) {
$images[] = $image;
}
foreach (array_diff($filenames, $images) as $image) {
$images[] = $image;
}
foreach ($images as $image) {
echo '<li><img src="' . $image . '" /></li>';
}
?>
This is assuming that $image from the $xml->image and $filename from your dir search are formatted the same. From what you've shown they are. If they aren't should be easy enough to run them through a quick regex to get them in a state where they are comparable.
Any who it looks like array_diff() is what you're looking for.
If you get a full list of the file names in the directory you could use PHP in_array and search for it in an array of your paths
$paths = array();
foreach ($xml->image as $image) {
$paths[] = $image['path'];
}
foreach ($filenames as $filename) {
if (!in_array($filename, $paths) {
$newImage = $xml->addChild('image');
$newImage->addAttribute('path', $filename);
}
}
// save adjusted xml file, assuming you have permission
$xml->asXML('/albums/1/photos.xml');
foreach ($xml->image as $image) {
echo '<li><img src="'.$image.'"></li>';
}
Related
I'm develop my websites and want to display all the images in a folder. I used the following code but occurred an error.
<?php
$sesi = Session::get('id');
$gambar = glob('archive_gambar/formulir/pendaftaran/'.$sesi.'/*');
for ($i=0; $i<count($gambar); $i++)
{
$single_image = $gambar[$i];
?>
<img src="<?php echo $single_image; ?>" class="img-responsive" style="margin-left: auto;margin-right: auto; margin-top: auto;margin-bottom: auto;width:75%;" alt="Tri">
<?php
}
?>
there is no error, the number of images is the same, but the picture does not appear.. like this
picture not appear
$dirname = "media/images/iconized/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
If the archive_gambar directory is at the root of the web site, try adding slash in front of the path
$gambar = glob('/archive_gambar/formulir/pendaftaran/'.$sesi.'/*');
if not, you must write the full path
Try with this, adjust the $dir variable to your needs:
/**
* This file: images.php
* This script read content of "images" directory as same level, and return filelist in array format
**/
$dir = "images/";
$images = array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($dir){
if(in_array($file, array('.', '..')) == FALSE){
$images[] = $file;
}
}
}
closedir($dh);
}
}
/**
* Print array to browswer
*/
echo '<pre>';
print_r($images);
/**
* Iterate $images array in foreach loop and display images with img tag (need to adjust directory to your needs).
*/
foreach ($images as $key => $image){
echo '<img src="images/'.$image.'" class="img-responsive" alt="image_'.$key.'">';
}
I try to dynamically populate an HTML page with 2 images, the first a full image and the second a reduced image, but as I can not do AND with a foreach.
In fact, the code is ok, but I want populate my HTML with twos pics of the same folder; but this code bring back all pictures, it doesn't no the diff between the Full image and the Thumbnail.
The script bring back all picture. My folder contain images with specific titles:
Full Image = *.jpeg
Thumbnail = *_Low.jpeg
I would like to be able to modify my code to insert the full in the first line and the thumbnail in the second line.
<?php
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
array().sort();
$nb = 1;
foreach($files as $file) {
if(fnmatch('*.jpg',$file)) {
$images[] = $file;
}
}
var_dump($images);
foreach ($images as $image) {
echo '<div class="cbp-item">'.'<a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/'.$image.'">'."\n"
.'<div class="cbp-caption-defaultWrap">'.'<img src="style/images/art/mairie/'.$image.'" alt="" /> </div>'."\n"
.'<div class="cbp-caption-activeWrap">'."\n"
.'<div class="cbp-l-caption-alignCenter">'."\n"
.'<div class="cbp-l-caption-body">'."\n"
.'<div class="cbp-l-caption-title"><span class="cbp-plus">'.'</span></div>'."\n"
.'</div>'."\n"
.'</div>'."\n"
.'</div>'."\n"
.'<!--/.cbp-caption-activeWrap --> '."\n"
.'</a> </div>'."\n";
}
?>
for the second line I would like to bring back the reduced photo, so to have
<div class="cbp-caption-defaultWrap"><img
src="style/images/art/mairie/Maurine_Tric-7399_Low.jpg" alt="" />
</div>
$images
Part of my $images array would look like this:
$images = [
"0" => "Maurine_Tric-7399.jpg",
"1" => "Maurine_Tric-7399_Low.jpg",
"2" => "Maurine_Tric-7407.jpg",
"3" => "Maurine_Tric-7407_Low.jpg",
"4" => "Maurine_Tric-7414.jpg",
"5" => "Maurine_Tric-7414_Low.jpg",
];
Desired Output
I'm trying to add one of the URLs in my array with large images, and the other with its thumbnail which are being differentiated with _Low:
<div class="cbp-item"><a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/Maurine_Tric-7399.jpg"> <div class="cbp-caption-defaultWrap"><img src="style/images/art/mairie/Maurine_Tric-7399_Low.jpg" alt="" /> </div>
Just use preg_match() instead of fnmatch(), matching only the thumbail images and marking the part before _Low.jpg as Subpattern.
Then you can easily construct the filename of both images from that stub:
<?php
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
array().sort();
$matches = NULL;
foreach ($files as $file) {
if (preg_match('/^(.+)_Low\.jpg$/', $file, $matches)) {
$images[] = $matches[1];
}
}
foreach ($images as $image) {
echo '<div class="cbp-item"><a class="cbp-caption fancybox-media" data-rel="portfolio" href="' . $dir . $image . '.jpg"> <div class="cbp-caption-defaultWrap"><img src="' . $dir . $image . '_Low.jpg" alt="" /></div>';
}
?>
If we wish to just add one URL for our images and one for their thumbs in the foreach, we might be able to define a $html variable and step by step add to it, then we would finally echo that, and our code would look like something similar to:
<?php
$html = '<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document sans titre</title>
</head>
<body>';
$html .= '<ul>';
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
$nb = 1;
foreach ($files as $file) {
if (fnmatch('*.jpg', $file)) {
$images[] = $file;
}
}
foreach ($images as $key => $image) {
if ($key % 2 == 0) {
$html .= '<div class="cbp-item">
<a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/' . $image . '">
<div class="cbp-caption-defaultWrap"><img src="style/images/art/mairie/' . $images[$key + 1] . '" alt="" /> </div>
<div class="cbp-caption-activeWrap">
<div class="cbp-l-caption-alignCenter">
<div class="cbp-l-caption-body">
<div class="cbp-l-caption-title"><span class="cbp-plus"></span></div>
</div>
</div>
</div>
</a>
</div>';
}
}
$html .= '</ul></body></html>';
echo $html;
Modifications
What we are modifying here is that we add an if to run every other time.
if ($key % 2 == 0) {
}
We add $key var in our foreach and finally we have two image links which we replace one of them with $images[$key+1], which one of them is for thumbs:
$image
$images[$key+1]
I'm trying to build a gallery for a friend, using PHP. Currently my script imports all the images from a "gallery" folder, and it displays them alphabetically, using automatically generated thumbnails and fancybox plugin.
Is it posible to sort them by date? It doesn't matter if it's the date when they were taken or the date when they were last modified. The code I use is below. Thanks in advance!
<?php
$path = 'gallery/';
$files = scandir('gallery/');
?>
<ul>
<?php foreach ($files as $file){
if ($file == '.' || $file == '..'){
echo '';
} else {
?>
<li><a class="fancybox" rel="group" href="<?php echo $path . $file; ?>"><img src="scripts/timthumb.php?src=<?php echo $path . $file; ?>&h=194&w=224&zc=1&q=100" /></a></li>
<?php } }?>
</ul>
this php function sorts your file by the last date it was modified.
Don't forget to put in the ignored files array which files you want to be ignored.
function scan_dir($dir) {
$ignored_files = array()
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file,$ignored_files) {
$files[$file] = filemtime($dir.'/'.$file);
}
}
arsort($files);
$files = array_keys($files);
if(is_null($files))
return false;
return $files;
}
You can refactor it a bit this was made really quicly. Hope this will work
I tried sort, Ksort, multiSort, nothing is working and I'm not sure why.I can use print_r and see that it is an array but it won't sort just keeps giving errors. I think it is because the values are floats but I may be wrong.
Here's a page with the array shown using print_r function:
http://forcedchange.testdomain.pw/gallery/
Here is my code:
<?php
$uploads = wp_upload_dir(); //Path to my gallery uploads folder
if ($dir = opendir($uploads['basedir'].'/gallery-2')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
$images = ksort($images); /* not working */
// echo '<pre>';
// echo print_r($images);
// echo '</pre>';
foreach($images as $image) {
echo '<figure><img src="';
echo $uploads['baseurl'].'/gallery-2/'. $image;
echo '" alt="" /></li>';
echo '<figcaption>';
echo '<p>' . erq_shortcode() . '</p>';
echo '</figcaption>';
echo '</figure>';
}
?>
Try using natsort($images) (don't know which result you want). It should sort the array like:
1.png
2.png
...
9.png
10.png
...
20.png
Assigning won't work because the sort-funcs return a bool... the sorting is done direct inside the given array.
$images=glob("/path/*.{jpg,png,gif}");
ksort($images);
foreach($images as $image)
{
...
... do something with basename($image);
...
}
I have the following code that reads the content of a folder
PHP Code:
<?
//PHP SCRIPT: getimages.php
header('content-type: application/x-javascript');
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="./images") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";' . "\n";
$curimage++;
}
}
closedir($handle);
}
sort($files);
return($files);
}
echo 'var galleryarray=new Array();' . "\n"; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
which spits out this the following code:
var galleryarray = new Array();
galleryarray[0] = "image1.jpg";
galleryarray[1] = "image5.jpg";
galleryarray[2] = "image2.jpg";
galleryarray[3] = "image4.jpg";
galleryarray[4] = "image8.jpg";
galleryarray[5] = "image7.jpg";
galleryarray[6] = "image0.jpg";
galleryarray[7] = "image3.jpg";
galleryarray[8] = "image6.jpg";
Now in my html file I want to echo something like
<img src="images/image0.jpg" />
<img src="images/image1.jpg"/>
...
...
How can I do that?
foreach($galleryarray as $img) {
echo "<img src='images/$img' />";
}
maybe this help u
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
if($handle = opendir("./images")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ ?>
<img src="/images/<?php echo $file; ?>">
<?php
}
}
}
assuming that you want to sort image name by value and then show the images. you first need to sort values by using function "asort"
asort($galleryarray);
foreach ($galleryarray as $key => $val) {
echo "<img src='images/{$val}'/>"
}
if you want to print and array
1) print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
2) use var_dump($array) to get more information of the content in the array like datatype and length.
3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website http://in3.php.net/manual/en/control-structures.foreach.php
Try changing the echo line in the function to this:
echo '<img src="images/' . $file . '" />' ;
Hope this will help :)
OR
Outside the function, use it like this:
$images = returnimages(); //will get the array containing the images
foreach($images as $img)
{
echo '<img src="images/' . $img . '" />';
}
Also, you have to include this line inside the if condition in the while loop:
$files[] = $file; //insert the file into the array. This array is what we are going to return from the function
Update
I have tested this code and it's working:
//PHP SCRIPT: getimages.php
header('content-type: application/x-javascript');
function returnimages($dirname="./images") {
$pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)"; // http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression/
$files = array();
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(preg_match($pattern, $file)){ //if this file is a valid image
$files[] = $file;
}
}
closedir($handle);
}
//sort($files); // http://php.net/manual/en/function.sort.php
natcasesort($files); // case insensitive "natural order" algorithm :: http://php.net/manual/en/function.natcasesort.php
return($files);
}
$images = returnimages(); //will get the array containing the images
foreach($images as $img)
{
echo '<img src="images/' . $img . '" />';
}
In my images folder, I have put 5 files for testing. And upon running it, it would give the following:
<img src="images/a.jpg" />
<img src="images/ba.jpg" />
<img src="images/ca.jpg" />
<img src="images/Copy (3) of a.jpg" />
<img src="images/Copy (4) of a.jpg" />