Pixiv の画像を一括ダウンロード

必要 → pixiv-api-php

#!/usr/bin/env php
<?php
require_once '/path/to/pixiv-api-php/pixiv.php';

$word = '南ことり';

$api = new PixivAPI();

$result = $api->search_works($word, 1, 10, 'tag');
$origin = [];
while ($result['pagination']['next'] != '') {
    foreach ($result['response'] as $value) {
        array_push($origin, [
            'filename' => $value['id'] . '_' . $value['title'] . '.jpg',
            'url' => $value['image_urls']['large'],
        ]);
    }
    $result = $api->search_works($word, $result['pagination']['next'], 10, 'tag');
}

foreach ($origin as $value) {
    echo 'start: ' . $value['url'] . PHP_EOL;
    download_image($value['url'], $value['filename']);
}

function download_image($url, $filename)
{
    $filepath = __DIR__ . '/dl/' . $filename;
    if (is_file($filepath)) {
        return;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36');
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.pixiv.net/');
    $result = curl_exec($ch);
    curl_close($ch);
    $fp = fopen($filepath, 'w');
    fwrite($fp, $result);
    fclose($fp);
}