php批量导入数据到mysql,html格式根据自己来,然后才能解析到数据库呀
<?php
// 连接数据库
$servername = "127.0.0.1";
$username = "root";
$password = "root";
$dbname = "数据库名";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接数据库失败: " . $conn->connect_error);
}
// 设置字符集
$conn->set_charset("utf8");
// HTML内容
$html = '
html格式
';
// 解析HTML内容并插入数据库
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
libxml_clear_errors();
// 提取字段值
$xpath = new DOMXPath($dom);
$items = $xpath->query('//div[@class="item-wrap item-li"]');
foreach ($items as $item) {
$img = $xpath->query('.//img[@class="el-image__inner"]', $item)->item(0);
$title = $xpath->query('.//div[@class="item-name"]', $item)->item(0)->textContent;
// 获取name字段的值
$name = '';
$div = $xpath->query('.//div[@data-en-name]', $item)->item(0);
if ($div !== null) {
$name = $div->getAttribute('data-en-name');
}
// 设置cate_id
$cate_id = 5; // 替换为您的自定义值
// 处理logo路径
$logo = ($img !== null) ? $img->getAttribute('src') : '';
$logo = str_replace("https://demo.ai.sslphp.com", "/storage/upload/20230808/", $logo);
// 获取当前时间的时间戳
$current_time = time();
// 插入数据库
$sql = "INSERT INTO ul_prompt_goods (cate_id, title, name, logo, create_time, update_time)
VALUES ('$catea_id', '$tit2le', '$nam2e', '$log2o', $curren2t_time, $current_time)";
if ($conn->query($sql) === TRUE) {
echo "记录插入成功<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
版权说明
文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!