dongsang6899 2019-02-19 10:44
浏览 59

使用PHP删除不在我的XML文档中的文件

I have an XML file that contains the SKU of products. I also have a folder that corresponds to this XML file.

Snippet from XML:
<Feed>
  <Product>
    <ItemCode>ALT-AAB-BL</ItemCode>
    <BaseItemCode>ALT-AAB</BaseItemCode>
    <StockCheckCode>ALT-AAB-BL</StockCheckCode>
 </Product>
  <Product>
    <ItemCode>ALT-AAB-L</ItemCode>
    <BaseItemCode>ALT-AAB</BaseItemCode>
    <StockCheckCode>ALT-AAB-L</StockCheckCode>
  </Product>
  <Product>
    <ItemCode>ALT-AAB-N</ItemCode>
    <BaseItemCode>ALT-AAB</BaseItemCode>
    <StockCheckCode>ALT-AAB-N</StockCheckCode>
 </Product>
</Feed>

I have been trying it with php but I am a junior and dont know where to start so I will give you some pseudo code.

if $domelement->ItemCode != filename.jpg{
    delte.jpg;
}

Yes this pseudo code is terrible. I basically am able to pull in the .xml file and was able to manipulate data.

I basically want to delete the files that is not present in the xml file and preserve the rest. I know how to appedn the ItemCode with .png if I need to.

<?php

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->load('altitude.xml');
$xpath = new DOMXPath($dom);

$query = sprintf('/Feed/Product/BaseItemCode');

foreach($xpath->query($query) as $record) {
//delete file that is not present in BaseItemCode
}

I just want the files not present in xml->BaseItemCode (which I will append with .png or .jpg) to be deleted from the folder.

  • 写回答

2条回答 默认 最新

  • dpkt17803 2019-02-19 10:51
    关注

    You need two lists: whitelist from XML and all items list from system.

    $dom = new DOMDocument;
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->load('altitude.xml');
    $xpath = new DOMXPath($dom);
    
    $query = sprintf('/Feed/Product/BaseItemCode');
    $xmlList = [];
    
    foreach($xpath->query($query) as $record) {
        $xmlList[] = $record->ItemCode . '.jpg';
        $xmlList[] = $record->ItemCode . '.png'; // If you can, use smarter way
    }
    

    $directory = '/full/path/to/dir';
    $dirList = array_diff(scandir($directory), array('..', '.'));
    
    $filesToDelete = array_diff($dirList, $xmlList);
    
    foreach ($filesToDelete as $file) {
        unlink($directory . DIRECTORY_SEPARATOR . $file);
    }
    
    评论

报告相同问题?