目前:我的代码保存了csv文件中给出的URL中的图像。
目标:根据同一csv文件中的值重命名已保存的图像,格式为:csv位置3,4,5,6,7,8
(例如100A1_https://www.instagram.com/p/BBzUXUFLrGH/_48.8486557_2.3481125)。
我试图将this stackoverflow示例合并到我的代码中。但无法,因为我绝望地失去了。
<?php
$destination = 'images/';
$dom = new DOMDocument;
$dir = "dir to photos";
$row = 0;
if (($handle = fopen("data/testcsvfile.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 100, ",")) !== FALSE /*&& $row < 1*/) {
$row++;
// number of fields in each row
$num = count($data);
// get url from position in csv
$url = $data[6];
echo $row . " " . $url. PHP_EOL;
if( strlen($url) > 0 ){
// if we have a url, get the contents
$page = file_get_contents($url);
//echo $page;
$dom->loadHTML($page);
// find url using meta tag
$my_tags = $dom->getElementsByTagName('meta');
// find which one is the image and grab and save
foreach ($my_tags as $tag) {
if($tag->getAttribute("property") == "og:image"){
$image_url = $tag->getAttribute('content');
echo $image_url . PHP_EOL;
$the_image = file_get_contents($image_url);
// rename file based on csv
// $newname = "$dir"."$names[3] $names[4] $names[5]".";
rename($newname);
file_put_contents( $destination . "img_" . $row . ".jpg", $the_image);
}
}
}
}
fclose($handle);
}
?>
&#13;
// test csv file
Mon,1,0,100,A,1,https://www.instagram.com/p/BBzUXUFLrGH/,48.8486557,2.3481125
Mon,1,0,100,A,1,https://www.instagram.com/p/BAe0tGULrC1/,48.85272468,2.347259349
Mon,1,0,100,A,1,https://www.instagram.com/p/_zik5YLrMf/,48.85356691,2.345645975
&#13;
答案 0 :(得分:0)
首先,您需要了解使用URL作为文件名是一件非常奇怪/糟糕的事情。 网址使用特殊字符,例如&#39; /&#39;这是某些操作系统中的目录分隔符。 如果你真的需要这样做,首先需要在文件名中转义该字符(或者更好地用非特殊字符替换它们,如下划线):
$newname = str_replace('/', '\/', $newname);
脚本的更新版本,可以安全地替换带下划线的斜杠:
<?php
$destination = 'images';
$dom = new DOMDocument;
if (($handle = fopen("data/testcsvfile.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 100, ",")) !== FALSE) {
$num = count($data);
// get url from position in csv
$url = $data[6];
echo $row . " " . $url. PHP_EOL;
if( strlen($url) > 0 ){
// if we have a url, get the contents
$page = file_get_contents($url);
//echo $page;
$dom->loadHTML($page);
// find url using meta tag
$my_tags = $dom->getElementsByTagName('meta');
// find which one is the image and grab and save
foreach ($my_tags as $tag) {
if($tag->getAttribute("property") == "og:image"){
$image_url = $tag->getAttribute('content');
echo $image_url . PHP_EOL;
$the_image = file_get_contents($image_url);
$destinationName = str_replace('/', '_', sprintf(
"%s%s%s_%s_%s_%s",
$data[3],
$data[4],
$data[5],
$data[6],
$data[7],
$data[8]
));
$destinationPath = sprintf(
"%s/%s",
$destination,
$destinationName
);
file_put_contents($destinationPath, $the_image);
}
}
}
}
fclose($handle);
}
?>