用于将图像从xml文件下载到本地文件夹的PHP代码

时间:2014-07-10 23:59:13

标签: php xml

我想将xml文件(fabfurnish.xml)中的所有图像下载到本地文件夹(输出)。根据 @ user1978142 编辑下面的代码后,我得到了所需的结果。感谢。

<?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/>";
    }
 }

 ?>

这是我正在使用的实际xml文件:

https://www.wetransfer.com/downloads/a88c2605cf038f8cc72603a0cf33904620140711034115/2ce9841bc9fd57063a0919de5f46862120140711034115/c1adbb

2 个答案:

答案 0 :(得分:2)

实际上,这非常简单。样品:

$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/>";
    }
}

答案 1 :(得分:0)

如果要像示例一样解析特定的xml文件,可以在getImagesFromXML($ xmlurl)中编辑如下代码。

foreach ($xml->product as $product) {
    foreach($product->image as $url) {
       $tmp = explode("/", $url);
       save($url, end($tmp), "output/");
    }
}