【发布时间】:2019-11-11 14:28:26
【问题描述】:
我在我的数据库中设置了一个表来从包含特殊字符的 json 文件中加载记录。我正在使用以下 PHP 代码上传记录。
<!DOCTYPE html>
<html>
<head>
<title>Insert Records</title>
</head>
<body>
<h1>Insert OER Records from JSON File</h1>
<h2>Outputs:</h2>
<?php
ini_set('memory_limit','2000M');
$url = 'path/filename.json';
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
$results = json_decode($contents, true);
include 'connection.php';
// Counter for number of records (x)
$x = 0;
foreach($results as $key => $value) {
$x = $x + 1;
foreach($value as $k => $v) {
$type = $value['type'];
$title = $value['title'];
$title = str_replace("'", "\'", $title);
$title = str_replace("(", "\(", $title);
$title = str_replace(")", "\)", $title);
$author = $value['author'];
$author = str_replace("'", "\'", $author);
$author = str_replace("(", "\(", $author);
$author = str_replace(")", "\)", $author);
$link = $value['link'];
$source = $value['source'];
$source = str_replace("'", "\'", $source);
$source = str_replace("(", "\(", $source);
$source = str_replace(")", "\)", $source);
$description = str_replace("'", "\'", $description);
$description = str_replace("(", "\(", $description);
$description = str_replace(")", "\)", $description);
$description = $value['description'];
$base_url = $value['base_url'];
$isbn_number = $value['isbn_number'];
$e_isbn_number = $value['e_isbn_number'];
$publication_date = $value['publication_date'];
$license = $value['license'];
$subject = $value['subject'];
$image_url = $value['image_url'];
$review = $value['review'];
$language = $value['language'];
$loc_collection = $value['loc_collection'];
$license_url = $value['image_url'];
}
$sql = "INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url')";
if (mysqli_query($conn, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
echo "This many records were entered into the database: " . $x;
mysqli_close($conn);
?>
<br/><br/><br/><br/><br/>
</body>
</html>
我的数据库设置为 utf8_general_ci。但是,带有特殊字符的记录无法正确显示。我得到这样的结果MuhÌ£ammad Kurd Ê»AliÌ。有什么我遗漏的吗?
【问题讨论】:
-
在代码中打印
mysqli_error($conn);是一个非常糟糕的主意,因为它可能会泄露敏感信息。更多解释见这篇文章:mysqli or die, does it have to die? -
这能回答你的问题吗? UTF-8 all the way through