使用PHP删除XML中BaseItemCode未对应的文件夹文件
Hey there! Let's get this file cleanup sorted out for you. You're already off to a great start with reading the XML—let's build on that step by step.
Step 1: Collect Unique BaseItemCode Values
First, we need to gather all the unique BaseItemCode values from your XML. Since multiple <Product> entries might share the same base code, we'll store them in an array and remove duplicates to avoid redundant checks.
Step 2: Fetch Image Files from the Target Folder
Next, we'll grab all the .jpg and .png files in your target folder. Using glob() makes this straightforward because it lets us filter files by extension directly.
Step 3: Delete Unmatched Files
For each image file, we'll strip off the file extension and check if the base name exists in our list of valid BaseItemCode values. If it doesn't, we'll delete the file (with some basic error handling to avoid crashes).
Here's the complete, commented code that puts this all together:
<?php // Load and parse the XML file $dom = new DOMDocument; $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->load('altitude.xml'); $xpath = new DOMXPath($dom); $query = '/Feed/Product/BaseItemCode'; // Collect unique BaseItemCode values $validBaseCodes = []; foreach ($xpath->query($query) as $record) { $baseCode = trim($record->nodeValue); // Only add unique codes to the array if (!in_array($baseCode, $validBaseCodes)) { $validBaseCodes[] = $baseCode; } } // Define your target folder path (update this to your actual folder) $targetFolder = './your-image-folder/'; // Get all .jpg and .png files in the folder $imageFiles = array_merge( glob($targetFolder . '*.jpg'), glob($targetFolder . '*.png') ); // Loop through each image file foreach ($imageFiles as $file) { // Get the filename without extension and folder path $fileName = pathinfo($file, PATHINFO_FILENAME); // Check if the filename (without extension) is NOT in our valid codes list if (!in_array($fileName, $validBaseCodes)) { // Attempt to delete the file if (unlink($file)) { echo "Deleted unmatched file: " . basename($file) . "\n"; } else { echo "Failed to delete: " . basename($file) . "\n"; } } } ?>
Key Notes for You:
- Update the folder path: Make sure
$targetFolderpoints to your actual image directory (don't forget the trailing slash!). - Error handling: The
echostatements are just for debugging—you can remove them or replace with logging once you're confident it works. - Safety first: Before running this on production files, test it on a copy of your folder! It's always smart to verify the logic doesn't delete anything you want to keep.
- Case sensitivity: PHP's
in_array()is case-sensitive by default. If your filenames andBaseItemCodevalues might have different cases (e.g.,ALT-AABvsalt-aab), addtrueas the third parameter toin_array()to make it case-insensitive, or normalize both to lowercase/uppercase.
内容的提问来源于stack exchange,提问作者Anton Roos

