dqsvnsad79721 2013-07-09 13:37
浏览 118
已采纳

来自csv的PHP file_get_contents()和file_put_contents

I'm trying to write a script that will allow for a two column .csv file (1st column with names, 2nd with image urls) to be read, and the images to then be saved to my hard drive using the first column as the saved file name. I'm able to get some images to save (all the files are created, but some are missing data). The naming convention works the way I want it to, but I need to get all of the files. Anyone care to take a look? Might be worth mentioning that I'm using MAMP but the image addresses in the .csv are all valid (I echoed out the image address with tags, so I know they work).

<?php
    //header('Content-Description: File Transfer');
    //header('Content-Disposition: attachment; filename ='
    //Eli's 2 column CSV grab-n-save file

    $file = 'Random.csv'; //put file path of .csv here
    $buffer = file_get_contents($file);
    //print_r($buffer);
    $pattern = '/[,
]/';

    $catch = preg_split($pattern, $buffer);
    $keep_track = 0;

    foreach($catch as $value)
    {
        if ($keep_track%2 == 0)
        {
        //if first column is sku
            $name = $value;
            $keep_track += 1;
        }
        elseif ($keep_track %2 == 1)
        {
            //if an image
            $name = str_replace(' ', '',$name);

            //Change pathname to MAMP specs
            $name2 =  '/Applications/MAMP/htdocs/picturegrab' . $name . '.jpg';

            file_put_contents($name2, file_get_contents($value), FILE_APPEND);
            //echo $value . '<br/>';
            $keep_track += 1;

            echo $name2 . '<br/>' . '<img src='.$value.'><br/>';
        }

    }
?>
  • 写回答

2条回答 默认 最新

  • doulianxi0587 2013-07-09 13:49
    关注

    some logic

    $file = fopen('Random.csv');
    $dir = '/Applications/MAMP/htdocs/picturegrab/';
    while (list($name, $img_link) = fgetcsv($file)) {
      $name = str_replace(" ", "", $name);
      copy($img_link, $dir.$name.'.jpg');
    }
    

    updated my example to make it more responsive

    also thx to Sam Green with his coment

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失