I need to go into a directory [named 'People'] and pull the names of folders and then construct some HTML that builds links using the contents of the directories.
I take a folder named: article-number-one and display a title, link, thumbnail, and excerpt based on the folder name.
Here is my code. It works except for the ordering. It is alphabetical. I want it to be by date created...newest on top:
<?php
$files = glob("people/*");
foreach($files as $file)
{
echo '<div class="block"><img src="people/'.basename($file).'/'.basename($file).'-thumbnail.jpg" height="180" width="320" alt="'.basename($file).'"/><br/><br/>';
echo ''.str_replace('-', ' ', basename($file, "")).'<br/><div class="excerpt">';
include 'people/'.basename($file).'/'.basename($file).'-excerpt.txt';
echo '</div><hr></div>';
}
?>
Please help me to order the resulting HTML newest to oldest.
Do this in several steps. This way you can check out how it proceeds and test each step separately.
// Get an array with all useful file info
$fileInfo = array_map(
function($filename) {
$short = basename($filename);
// Excerpt
$excerpt = $filename . DIRECTORY_SEPARATOR . $short . '-excerpt.txt';
if (is_readable($excerpt)) {
$text = trim(file_get_contents($excerpt));
} else {
$text = 'Excerpt not available';
}
return [
'full' => $filename,
'base' => $short,
'thumb' => $filename . DIRECTORY_SEPARATOR . $short . '.jpg',
'name' => ucwords(str_replace('-', ' ', $short)),
'date' => filectime($filename),
'text' => $text,
];
},
glob("people/*", GLOB_ONLYDIR)
);
To sort the array:
// Now sort the array. Have a function decide when a file is before another
usort($fileInfo, function($info1, $info2) {
if ($info1['date'] < $info2['date']) {
return 1;
}
if ($info1['date'] > $info2['date']) {
return -1;
}
return 0;
});
Finally you get the HTML in a variable. As a rule, it's good to have as few echo/print's as possible. Mixing PHP and output can be a maintenance nightmare.
// Get the HTML. You could put this in a .html file of its own
// such as 'template.html' and read it with
// $template = trim(file_get_contents('template.html'));
$template = <<<INFO2HTML
<div class="block">
<a href="{base}"><img
src="{thumb}"
height="180" width="320"
alt="{base}"/></a>
<br />
<br />
{name}
<br />
<div class="excerpt">{text}</div>
<hr />
</div>
INFO2HTML;
// Repeat the parsing of the template using each entry
// to populate the variables.
$html = implode('', array_map(
function($info) use($template) {
return preg_replace_callback(
'#{(.*?)}#',
function($keys) use ($info) {
return $info[$keys[1]];
},
$template
);
},
$fileInfo
));
print $html;
Testing
$ mkdir people
$ mkdir people/joe-smith
$ echo "this is the excerpt" > people/joe-smith/joe-smith-excerpt.txt
$ touch people/joe-smith/joe-smith-thumbnail.jpg
$ ls -R people
people:
joe-smith
people/joe-smith:
joe-smith-excerpt.txt
joe-smith-thumbnail.jpg
Sample run outputs:
<div class="block">
<a href="joe-smith"><img
src="people/joe-smith/joe-smith.jpg"
height="180" width="320"
alt="joe-smith"/></a>
<br />
<br />
Joe Smith
<br />
<div class="excerpt">this is the excerpt</div>
<hr /> </div>
usort($files, function($a, $b) {
return ($a['date'] < $b['date']) ? -1 : 1;
});
Related
I'm Using the following code to fetch images from wikipedia api but at the moment it is giving me random images on that keyword like if I search "spain " it will give me random images with word spain but I need the images of places in spain like we get in wikipedia.
Can any one help me with that?
<form action="" method="get">
<input type="text" name="search">
<input type="submit" value="Search">
</form>
<?php
if(#$_GET['search']){
function get_wiki_image( $search, $limit) {
$streamContext = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$url = 'https://en.wikipedia.org/w/';
$url .= '/api.php?action=query&format=json&list=allimages&aifrom=' . $search . '&ailimit=' . $limit;
$context = stream_context_create($streamContext);
if(FALSE === ($content = #file_get_contents($url, false,$context)) ) {
return false;
} else {
$data = json_decode($content,true);
$ret = array();
foreach($data['query']['allimages'] as $img) {
$ret[] = $img['url'];
}
return $ret;
}
}
$search = ucwords($_GET['search']);
$images = get_wiki_image($search,500);
foreach($images as $img) {
echo "<img src='{$img}' height='50' width='50'>";
}
}
?>
You can use the PageImages API for this purpose. Generally, it returns you the first image in an article, however, depending on the configurations of Wikipedia it might return a different image in some cases.
To get for example the image of the "Barcelona" article, call https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Barcelona&piprop=original.
If you need the picture in a certain size, you can also call https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Barcelona&pithumbsize=250.
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 have search before & don't find answer
http://i.stack.imgur.com/6mZRz.png
I want to get url of image after " : "
I am using simple dom html
My listing is..
include 'simple_html_dom.php';
$target = 'http://search.aol.com/aol/image?q=aku+ganteng';
$html = file_get_html($target);
foreach($html->find("div[class=inner]") as $f){
$crot = $f->find("img",0)->src;
echo '<img src="'.$crot.'"/><br/>';
}
The HTML listing
<div class="inner">
<span class="imgc"></span>
<a href="imageDetails?s_it=imageDetails&q=aku+ganteng&img=http%3A%2F%2Fsd.keepcalm-o-matic.co.uk%2Fi%2Fjarene-ibuk-ku-aku-ganteng-cok-d.png&v_t=topsearchbox.image&host=http%3A%2F%2Fwww.keepcalm-o-matic.co.uk%2Fp%2Fjarene-ibuk-ku-aku-ganteng-cok-d%2F&width=129&height=151&thumbUrl=https%3A%2F%2Fencrypted-tbn1.gstatic.com%2Fimages%3Fq%3Dtbn%3AANd9GcQD_uhCuZ6yy19yB452fbEQAabTwa3xrOyVdArDf2COKl3AKKYX30dxAht7Nw%3Asd.keepcalm-o-matic.co.uk%2Fi%2Fjarene-ibuk-ku-aku-ganteng-cok-d.png&b=image%3Fs_it%3DimageResultsBack%26v_t%3Dtopsearchbox.image%26q%3Daku%2Bganteng%26oreq%3D310738f642cd4b029e1f8c897168a385&imgHeight=700&imgWidth=600&imgTitle=JARENE+IBUK%26%2339%3BKU+AKU+GANTENG+COK&imgSize=39960&hostName=www.keepcalm-o-matic.co.uk" onclick="return sl.sl(null,null,null,this,'image_results',1)">
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQD_uhCuZ6yy19yB452fbEQAabTwa3xrOyVdArDf2COKl3AKKYX30dxAht7Nw:sd.keepcalm-o-matic.co.uk/i/jarene-ibuk-ku-aku-ganteng-cok-d.png" width="129" height="151" alt="JARENE IBUK'KU AKU GANTENG COK" title="JARENE IBUK'KU AKU GANTENG COK"></a>
</div>
I want get part of this
sd.keepcalm-o-matic.co.uk/i/jarene-ibuk-ku-aku-ganteng-cok-d.png
How to get full url target?
You probably need this:
$crot= "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQD_uhCuZ6yy19yB452fbEQAabTwa3xrOyVdArDf2COKl3AKKYX30dxAht7Nw:sd.keepcalm-o-matic.co.uk/i/jarene-ibuk-ku-aku-ganteng-cok-d.png"
preg_match_all('/.*:(.*?)$/sim', $crot, $part, PREG_PATTERN_ORDER);
$part = $part[1][0];
echo $part;
Output:
sd.keepcalm-o-matic.co.uk/i/jarene-ibuk-ku-aku-ganteng-cok-d.png
Full code:
<?
include 'simple_html_dom.php';
$target = 'http://search.aol.com/aol/image?q=aku+ganteng';
$html = file_get_html($target);
foreach($html->find("div[class=inner]") as $f){
$crot = $f->find("img",0)->src;
$ahh = str_replace("thumbs","download",$crot);
$wall = str_replace("t1","1920x1080",$ahh);
preg_match_all('/.*:(.*?)$/sim', $crot, $part, PREG_PATTERN_ORDER);
$part = $part[1][0];
echo $part; //this is what you want.
echo "<a href='$crot'><img src='$crot'/></a><br/>";
}
?>
This is the code which loads images with different Prefix and the prefix is printed under every image.
I need Prefix as a Title of every set of images as Category of Images
CODE :
$images = glob($dirname . "*.jpg");
foreach ($images as $image) {
if (strpos($image, '#') !== false) {
} else {
?>
<li><?php $mn_img = str_replace("/thumbs", "", $image); ?>
<div class="th [radius]">
<a href="<?php echo $mn_img ?>"><img align="middle"
src="<?php echo $image; ?>"> </a>
</div>
<p style="text-align: center">
<?php
$str = $mn_img;
$s = end(explode("/", $str));
$e = explode(".", $s);
$n = explode('-', $e[0]);
$nm = $n[0];
if ($nm === 'non') {
echo 'general';
} else {
$title = str_replace("_", " ", $nm);
echo $title;
}
?>
</p>
</li>
<?php }
}
I expect the possibility :)
MY Prefix Format is
Manager_fileoriginalname_random.jpg
Manager_fileoriginalname_random.jpg
Manager_fileoriginalname_random.jpg
Manager_fileoriginalname_random.jpg
Prefix is "Manager"
Matketing_fileoriginalname_random.jpg
Matketing_fileoriginalname_random.jpg
Matketing_fileoriginalname_random.jpg
Matketing_fileoriginalname_random.jpg
Prefix is "Marketing"
is the preg_match function is what you want :
$returnValue = preg_match( '/(.*)_.*_.*$/', 'Manager_fileoriginalname_random.jpg', $matches );
in $matches[1] you have the prefix, you just need to remplace 'Manager_fileoriginalname_random.jpg' by your var $mn_img
If i can make and advise, can use parse_url() to extract url components : http://php.net/manual/fr/function.parse-url.php
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" />