SyntaxError: 意外的标记 '<', "<br /> <b>"... 是无效的 JSON

问题描述 投票:0回答:0

语法错误:意外的标记'<', "
“...不是有效的 JSON

我正在尝试使用 PHP 将电影信息保存到数据库中,但出现以下错误:

语法错误:意外的标记'<', "
“...不是有效的 JSON

我不确定是什么原因导致此错误或如何修复它。这是我的 PHP 代码:

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');

//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);

// Connect to the database
$db_host = '*********';
$db_user = '******';
$db_pass = '************';
$db_name = 'my_movies';
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// If the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the request body and decode the JSON data
    $data = json_decode(file_get_contents('php://input'), true);
    // Loop through the movies that were sent in the request body
    foreach ($data['movies'] as $movie) {
        $movie_id = $movie['id'];
        // Fetch the movie details from the API
        $api_key = 'your_api_key';
        $url = "https://api.themoviedb.org/3/movie/$movie_id?api_key=$api_key";
        $data = file_get_contents($url);
        $movie_data = json_decode($data, true);
        $title = mysqli_real_escape_string($conn, $movie_data['title']);
        $overview = mysqli_real_escape_string($conn, $movie_data['overview']);
        $poster_path = mysqli_real_escape_string($conn, $movie_data['poster_path']);
        // Insert the movie into the database
        $sql = "INSERT INTO seen_movies (movie_id, title, overview, poster_path) VALUES ('$movie_id', '$title', '$overview', '$poster_path')";
        mysqli_query($conn, $sql);
    }
}

// Fetch all movies from the database
$sql = "SELECT * FROM seen_movies";
$result = mysqli_query($conn, $sql);

// Create an array to store the movies
$movies = array();
if (mysqli_num_rows($result) > 0) {
    // Loop through each row in the result set
    while ($row = mysqli_fetch_assoc($result)) {
        // Add the movie to the movies array
        $movies[] = $row;
    }
}

// Close database connection
mysqli_close($conn);

// Set the response header to JSON
header('Content-Type: application/json');

// Convert the movies array to JSON and send the response
echo json_encode($movies);

任何帮助将不胜感激。谢谢!

php sql apache
© www.soinside.com 2019 - 2024. All rights reserved.