0

I have a local XAMP install on my Mac. I have this code:

foreach (new DirectoryIterator('test') as $fileInfo) {
    if ($fileInfo->isDot() && $fileInfo->getBasename() !== '.DS_Store') {
        continue;
    }

    $xmlFile = "test/" . $fileInfo->getFilename() . "/content.xml";

    if (file_exists($xmlFile)) {
        $xml = simplexml_load_file($xmlFile);
        foreach ($xml->infos as $infos) {
            echo "<li><a href='#tab_3' data-toggle='tab'>$infos->bezeichnung</a></li>";
        }
    }
}

The problem is that I get an error that says that the file .DS_Store cannot be opened. I thought my code filtered out the .DS_Store directory. It's clear that this file cannot be opened. It is a mac specific folder.

TheCrazyProfessor
  • 919
  • 1
  • 15
  • 31
DragonStyle
  • 145
  • 11

2 Answers2

4

Your filter is saying "if it is a dot file and it is not .DS_Store, skip it" which is the opposite of what I believe you want. Try this:

if ($fileInfo->isDot() || $fileInfo->getBasename() === '.DS_Store') {
    continue;
}

Which says "if it is a dot file (. or ..) or it is .DS_Store, skip it."

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
2

.DS_Store is a file, not a folder.

Your code is inappropriately assuming that anything returned by the directory iterator will be a folder and looking for a content.xml file inside it; this fails for regular files. .DS_Store happens to be a file, but the same issue would arise with any other file which happened to be in this directory.

Use the isdir method of DirectoryIterator to check whether the current item is a directory before trying to open files within it. Once you do this, you won't need a special case for .DS_Store.