根據歌手id採集歌曲:
🔒 隱藏內容:會員可查看
<?php
$shuju_file = "shuju.txt";
$shuju = @json_decode(@file_get_contents($shuju_file),true);
$id = empty($shuju['id'])?0:$shuju['id'];
$page = empty($shuju['page'])?0:$shuju['page'];
$urls = file_get_contents("songid.txt");
$array = explode(PHP_EOL,$urls);
$api = json_decode(file_get_contents("http://music.4s5.cn/artist/songs?id={$array[$id]}&limit=100&offset={$page}"),true);
echo "<p>當前歌手id:{$array[$id]}----歌手數".count($array)."----當前歌手序號:{$id}---當前歌手歌曲量:{$shuju['total']}---當前採集到歌手歌曲第{$shuju['page']}首</p>";
// die;
// 數據庫信息
$host = "localhost"; // 數據庫主機名
$username = "music163"; // 數據庫用戶名
$password = "dDHAHeiCR8rXyb68"; // 數據庫密碼
$database = "music163"; // 數據庫名稱
// 創建連接
$conn = new mysqli($host, $username, $password, $database);
// 檢查連接是否成功
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
if(!empty($api['songs'])){
foreach ($api['songs'] as $v){
// print_r($v);
insertData($conn, "INSERT INTO `music163`.`hm_song` (`id`, `songid`, `song`) VALUES (NULL, '{$v['id']}', '".addcslashes($v['name'],"'")."');",$v['name']);
}
}
// 關閉連接
$conn->close();
function insertData($conn, $sql,$name = '') {
// 執行插入操作
if ($conn->query($sql) === TRUE) {
echo "<p style='color:green'>數據入庫成功---{$name}"."</p>";
} else {
echo "<p style='color:red'>已採集過本歌曲: " . $conn->error ."----{$name}</p>";
}
}
// die;
$total = $api['total'];
if($shuju['page'] <= $total){
$shuju['page'] = $shuju['page'] + 100;
file_put_contents($shuju_file,json_encode([
'id' => $shuju['id'],
'page' => $shuju['page'],
'total' => $api['total'],
]));
go();
}else if(count($array) >= $shuju['id']){
$shuju['id']++;
file_put_contents($shuju_file,json_encode([
'id' => $shuju['id'],
'page' => 0,
'total' => $api['total'],
]));
echo "正在切換歌手.....";
go();
}else{
echo "所有歌手採集完成";
}
function go(){
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
echo '<meta http-equiv="refresh" content="'.mt_rand(0,1).'; url='.$url.'">';
}