Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I wanted to download all the images in an xml file (fabfurnish.xml) to a local folder (output). After editing the code below according to #user1978142 i got the desired result. Thanks.
<?php
$xml = simplexml_load_file('input/fabfurnish.xml'); // your xml
foreach($xml->product as $url) {
$url = (string) $url->image;
$filename = basename($url); // get the filename
if(file_exists($filename)) {
echo "file <strong>$filename</strong> already exists <br/>";
} else {
$img = file_get_contents($url); // get the image from the url
file_put_contents('output/'.$filename, $img); // create a file and feed the image
echo "file <strong>$filename</strong> created <br/>";
}
}
?>
This is the actual xml file i am working with:
https://www.wetransfer.com/downloads/a88c2605cf038f8cc72603a0cf33904620140711034115/2ce9841bc9fd57063a0919de5f46862120140711034115/c1adbb
Actually, this is quite straightforward. Sample:
$xml = simplexml_load_file('fabfurnish.xml'); // your xml
foreach($xml->product as $url) {
$url = (string) $url->image;
$filename = basename($url); // get the filename
if(file_exists($filename)) {
echo "file <strong>$filename</strong> already exists <br/>";
} else {
$img = file_get_contents($url); // get the image from the url
file_put_contents($filename, $img); // create a file and feed the image
echo "file <strong>$filename</strong> created <br/>";
}
}
If you want to parse specific xml file like your sample, you can edit as following code in getImagesFromXML($xmlurl).
foreach ($xml->product as $product) {
foreach($product->image as $url) {
$tmp = explode("/", $url);
save($url, end($tmp), "output/");
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 18 days ago.
Improve this question
I have 100 html files, and i want to add a line of code (at the end) to all of them.
How is this possible ?
Something like a script which appends that line into all html files
I tried searching but did not find anything.
You can use :
<?php
$folder = '/path/to/html/files';
$line_to_add = '<p>your line/p>';
foreach (glob("$folder/*.html") as $file) {
$contents = file_get_contents($file);
file_put_contents($file, $line_to_add . PHP_EOL . $contents);
}
Your question is quite unclear, because you didn't specify where you are going to append this lane? Here is a starting point:
<?php
$path = '/path/to/html/files';
$code_to_add = '<p>This line was added by a script.</p>';
$files = scandir($path); // get an array of all the files in the directory specified by $path.
foreach ($files as $file) { // Iterate over files
if (substr($file, -5) == '.html') { // hecking if each file has a ".html" extension.
$file_path = $path . '/' . $file;
$file_contents = file_get_contents($file_path); // read the contents
file_put_contents($file_path, $file_contents . $code_to_add); // put new content, you can modify it.
}
}
?>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am moving images from xcode to an online platform and i need to generate a JSON file from a directory structure (images only) that lists the folders, and the images in those folders, with complete URL (online) AND date they where added.
I am a COMPLETE noob with PHP web stuff, so am really lost at the moment.
I found the following code, but that does not do anything so far, and does not travels into directory's.
<?php
/*
JSON list of all images files in current directory
*/
$dir = ".";
$dh = opendir($dir);
$image_files = array();
while (($file = readdir($dh)) !== false) {
$match = preg_match("/.*\.(jpg|png|gif|jpeg|bmp)/", $file);
if ($match) {
$image_files []= $file;
}
}
echo json_encode($image_files);
closedir($dh);
?>
The following code works for me. Found it here.
I've only modified the echo, added the regex and the time. I hope this answers your question.
<?php
function getDirContents($path) {
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$files = array();
foreach ($rii as $file) {
if (!$file->isDir() && preg_match("/.*\.(jpg|png|gif|jpeg|bmp)/", $file)) {
$files[] = [
'path' => $file->getPathname(),
'c_time' => $file->getCTime()
];
}
}
return $files;
}
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'files' => getDirContents('.')
]);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am new to the world of PHP.
I am trying a simple program.
open a file
read the first line
line contains another file name
Form file path for this filename
check if it exists or not.
It always return file does not exists but actually the file exists in the computer.
When I hardcode the filepath in the above step 5,it starts detecting file exists and evaluates true.
Below is my code:
<?php
$filepath = "/Users/aashok";
$x="myfile";
$file1="$filepath/$x";
function checkFileExists($newFile){
if(file_exists($newFile)){
echo "exists";
}else{
var_dump($newFile);
}
}
if(file_exists($file1)){
$f = fopen($file1, 'r');
$file2 = fgets($f);
fclose($f);
$filepath2="$filepath/$file2";
// echo "filepath2 : $filepath2 ------ ";
var_dump($file2);
var_dump($filepath2);
checkFileExists($filepath2);
}else{
echo "does not exists";
}
?>
The output I get is :
string(8) "myfile2 " string(22) "/Users/aashok/myfile2 " string(22) "/Users/aashok/myfile2 "
The directory structure is :
aashok$ ls|grep myfile
myfile
myfile2
aashok$ pwd
/Users/aashok
aashok$ cat myfile
myfile2
I am cluesless as what is wrong here.Can someone please help with this.
If file1 contains more than one line, then the call to fgets will include the line-ending. When you pass this to file_exists, it will return false, since obviously the filename on disk doesn't contain one.
From the manual:
Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first).
If you trim the line-endings from $file2 first, this should work correctly:
Change
$file2 = fgets($f);
to
$file2 = rtrim(fgets($f));
Because your $file2 is contain just file name, right? it relative path.
Try this code fix your problem:
$filepath = "/Users/abhinav";
$src = "file1";
$file1 = "$filepath/$src";
function checkFileExists($newFile)
{
if(file_exists($newFile))
{
echo "exists";
}else{
echo "file does not exists :$newFile ";
}
}
if(file_exists($file1))
{
$f = fopen($file1, 'r');
$file2 = trim(fgets($f)); // remove start/end spaces,new line, etc
//If file is relative with current file, you need this
$file2 = dirname($file1) . DIRECTORY_SEPARATOR . $file2;
fclose($f);
echo "file1 :$file1 ";
//assume it return /Users/abhinav/newFile2 which is existing
echo "filepath2 : $file2 ";
checkFileExists($file2);//evaluates false in function
checkFileExists("/Users/abhinav/newFile2");//evaluates true in function
}else
{
echo "does not exists";
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have several ziped files in a folder. I would like to unzip them to a specified folder. I have the following php code:
$path = "docs/" . $ID;
$files = scandir("temp" . '/' . $ID );
foreach ($files as $athely){
$zip = new ZipArchive;
$res = $zip->open($athely);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($path);
$zip->close();
echo "WOOT! $file extracted to $path";
} else {
echo "Doh! I couldn't open $athely";
}
}
It is not working. What am I doing wrong?
The problem was you are not using full path for opening the zip. Another thing to notice is if more than one zip file have folder with same name then one folder will overwrite the other.
<?php
$path = "docs/" . $ID;
$files = scandir("temp" . '/' . $ID );
foreach ($files as $athely){
if($athely=="." || $athely=="..") continue;
$target_path = "temp/".$ID."/".$athely;
$file = $athely;
$zip = new ZipArchive;
$res = $zip->open($target_path);
if ($res === TRUE) {
$zip->extractTo($path);
$zip->close();
echo "WOOT! $file extracted to $path";
} else {
echo "Doh! I couldn't open $athely";
}
}
?>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I need to find the oldest file in a directory, oldest file in all (including, directories, subdirectories of a particular folder)
Folder 1
- dir 1
- dir 1.1
- file 1
- dir 2
- dir 2.1
- file 2
if file 2 is oldest , I need to able to get oldest file (file 2) by passing main directory name (Folder 1)
my solutions is
function get_oldest_file($dir) {
$filemdate = array();
print $dir.PHP_EOL;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
$files[] = $file;
print $file.PHP_EOL;
}
foreach ($files as $eachfile) {
if (is_file($dir.eachfile)) {
$file_date[$eachfile] = filemtime($dir.$eachfile);
print $filemdate[$eachfile].PHP_EOL;
}
}
}
closedir($handle);
asort($filemdate, SORT_NUMERIC);
reset($filmdate);
$oldest = key($filemdate);
print "Oldest is : ".$oldest;
return $oldest;
}
echo get_oldest_file("/path/---")
Thanks !
What about?
function workerFunction($currentDir, $oldestFile)
foreach (glob($currentDir.'/*') as $file) {
if (is_dir($file)) {
if ((basename($file)!='.') && (basename($file)!='..')) {
$oldestFile = workerFunction($file, $oldestFile);
}
} else {
$mtime = filemtime($file);
if ($mtime <= $oldestFile['mtime']) {
$oldestFile['mtime'] = $mtime;
$oldestFile['path'] = $file;
}
}
}
return $oldestFile;
}
function searchForOldestFile($dir) {
$oldestFile['mtime'] = time();
$oldestFile['path'] = null;
$oldestFile = workerFunction($dir, $oldestFile);
return $olderstFile['path'];
}
I don't have the PHP environment for debugging, but at least with some little fixes it could work as you need.
Let me explain, so you would be able to use it easily:
searchForOldestFile function is the interface that your script should call; workerFunction does the "magic" (if it work :)), keeping in $oldestFile a reference to the current oldestFile.