0

I need to recursively traverse a certain directory and list all of the files inside of it I have found an example on the PHP website however after further searching I am not able to find a solution to my problem. The problem is that it prints out the entire path but I only want to echo out the first containing folder of the file. So for example as it sits now I get this output:

/var/www/example.com/public_html/images/6.Blah/_Original/DSC_0174.jpg

But I want it to echo:

_Original/DSC_0174.jpg

or

/_Original/DSC_0174.jpg

Here is the code I am using:

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
    echo "$name\n";
}

?>
2
  • 1
    have you tried using basename()? Commented Apr 2, 2014 at 17:58
  • 1
    basename only gets me the file name I need the directory that contains it plus the file name Commented Apr 2, 2014 at 18:01

1 Answer 1

1

This is a formatting issue, you can approach it in many different ways. One way will be to split the string into an array and grab the last two elements.

foreach($objects as $name => $object){
    $pieces = explode("/",$name);
    $length = count($pieces);
    $result = $pieces[$length-2]."/".$pieces[$length-1];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.