XML Movie Database (zonder MySQL)

Gepost door BartjeNL op 30-03-2011 23:45.

XML Movie Database is een PHP website/script waarmee je naar een film kunt zoeken, en vervolgens toevoegen aan je 'collectie'. Als je op een film zoekt, maakt het script automatisch hiervan een xml bestand aan, en haalt hij hieruit de benodigde informatie.

Er is geen MySQL database nodig, aangezien elk XML bestand voor een film aan wordt gezien, en deze dus zo wordt ingeladen.

Het enige wat je hiervoor nodig hebt om dit allemaal werkend te krijgen is een (gratis) API key van de website TMDb (waar dit script de film gegevens vandaan haalt). Deze is aan te vragen op hun website: http://www.themoviedb.org/. Vervang vervolgens jou API Key met 'HIER JE TMDB API KEY' in PHP/addMovie.php.

Waarschijnlijk zul je ook nog de benodigde schrijf rechten (CHMOD) moeten toekennen aan de XML map. Daarna zal alles moeten werken en ben je klaar om films toe te voegen!

Bestanden van dit script

XML Movie Database/img/imdb.png

De inhoud van dit bestand kan niet weergegeven worden.

XML Movie Database/img/imdb_no.png

De inhoud van dit bestand kan niet weergegeven worden.

XML Movie Database/img/loading.gif

De inhoud van dit bestand kan niet weergegeven worden.

XML Movie Database/img/noPhotoAvailable.jpg

De inhoud van dit bestand kan niet weergegeven worden.

XML Movie Database/img/noPhotoAvailable.png

De inhoud van dit bestand kan niet weergegeven worden.

XML Movie Database/img/youtube.png

De inhoud van dit bestand kan niet weergegeven worden.

XML Movie Database/img/youtube_no.png

De inhoud van dit bestand kan niet weergegeven worden.

XML Movie Database/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="./JS/getMovies.js"></script>
<script type="text/javascript" src="./JS/addMovie.js"></script>
<script type="text/javascript" src="./JS/deleteMovie.js"></script>
<script type="text/javascript">

var numberOfMovies = 0;

$(document).ready( function()
{
	getMovies();
});
</script>

<link rel="stylesheet" href="style.css" type="text/css" media="screen" />

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>XML Movie Database</title>
</head>

<body>
<div id="wrapper">
    <div id="header">
        <div id="logo">XML Movie Database</div>
        <div id="rightmenu"><input name="movieTitle" type="text" value="Movie Title" onfocus="if(this.value == 'Movie Title') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Movie Title';}"  /><div id="submit"><input name="submit" type="button" value="Add Movie" /></div>
        </div>
    </div>
    <div id="movies">
    </div>
</div>
</body>
</html>

XML Movie Database/JS/addMovie.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// JavaScript Document

$(document).ready( function()
{
	$("#submit").click(function()
    {
		$("#submit").html('<img src="img/loading.gif">');
		$.ajax(
        {
            type: "POST",
			dataType: 'json',
			url: "PHP/addMovie.php",
            data: {            
					movieTitle : $("input[name=movieTitle]").val(),
                     },
			success: function(data)
                {
                    if (data == "Illegal Characters")
                        {
                            alert ("Special characters are not allowed");
                        }
                            
                    else if (data == "Movie not found")
                        {
                            alert ("Movie not found");
                        }
						
					$("#submit").html('<input name="submit" id="submit" type="button" value="Add Movie" />');
					$("input[name=movieTitle]").val("Movie Title");
                    var moviesTitles = [];
                    var moviesDescriptions = [];
                    var moviesPosters = [];
                    var moviesYears = [];
                    var moviesIMDB = [];
                    var moviesTrailers = [];
                    var moviesXmlTitles = [];
								
					$("#movies").html("");
					getMovies();
                }
        });
    });
});

XML Movie Database/JS/deleteMovie.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// JavaScript Document

$(document).ready( function()
{
    $(".delete").live('click', function()
    {
        var row = $(this).parent().parent();
				
		$.ajax(
        {
            type: "POST",
			dataType: 'json',
			url: "PHP/deleteMovie.php",
            data: {            
					movieTitle : row.find('h1').html(),
                     },
			success: function(data)
                {
					numberOfMovies--;
					row.fadeOut(function()
                    {                    
                        if (numberOfMovies == 0)
                            {
								$("#movies").html("");
								$("#movies").append("No movies have been added");
                            }
                    });
                }
        });
    });
});

XML Movie Database/JS/getMovies.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// JavaScript Document

function getMovies()
    {
        var moviesTitles = new Array();
        var moviesDescriptions = new Array();
        var moviesPosters = new Array();
        var moviesYears = new Array();
        var moviesIMDB = new Array();
        var moviesTrailers = new Array();
        var moviesXmlTitles = new Array();
		
		$.getJSON('PHP/getMovies.php', function(data) 
                    {
                        if (data.moviesTitles.length == 0)
                            {
								$("#movies").append("No movies have been added");
                            }
                        else
                            {	
						
								$("#movies").append('<table width="100%"><thead><tr><th width="70%"></th><th width="10%">Year</th><th width="10%">Info</th><th width="10%">Actions</th></tr></thead><tfoot></tfoot></table> ');    
                                
                                for (var x = 0; x < data.moviesTitles.length; x++)
                                {
									numberOfMovies++;
									
									moviesTitles.push(data.moviesTitles[x]);
									moviesDescriptions.push(data.moviesDescriptions[x]);
									moviesPosters.push(data.moviesPosters[x]);
									moviesYears.push(data.moviesYears[x]);
									moviesIMDB.push(data.moviesIMDB[x]);
									moviesTrailers.push(data.moviesTrailers[x]);
                                                                
                                    if (moviesIMDB[x] == "na")
                                        {
											imdb = '<img src="img/imdb_no.png">';
                                        }
                                    else
                                        {
											imdb = '<a href="http://www.imdb.com/title/'+moviesIMDB[x]+'"><img src="img/imdb.png"></a>';
                                        }
                                        
                                    if (moviesTrailers[x] == "na")    
                                        {
											youtube = '<img src="img/youtube_no.png">';
                                        }
                                        
                                    else
                                        {
											youtube = '<a href="'+moviesTrailers[x]+'"><img src="img/youtube.png"></a>';
                                        }
																	
									$("#movies thead").before('<tbody class=movie'+x+'><tr><td><table><tr><td><img src="'+moviesPosters[x]+'" width="120" /></td><td valign="top"><div id="movieDescription"><h1>'+moviesTitles[x]+'</h1><p>'+moviesDescriptions[x]+'</p></div></td></tr></table></td><td valign="top">'+moviesYears[x]+'</td><td valign="top">'+imdb+youtube+'</td><td valign="top"><a href="#" class="delete" onclick="return false">Delete</a></td></tr>');
                                }
                            }
                    });
    }

XML Movie Database/PHP/addMovie.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php

include ("TMDb/TMDb.php");

$movieTitle = $_POST['movieTitle'];

if ( ! preg_match("/^[a-zA-Z0-9]+$/", $movieTitle) ) 
{
    echo json_encode("Illegal Characters");
}

else
{

    $tmdb = new TMDb('2bcff99b7f5691f5a694ce133bcbf715');
    $moviesResult = $tmdb->searchMovie($movieTitle);
    $moviesArray = json_decode($moviesResult);
    
    $movieId = $moviesArray[0]->id;
    $tmdbXML = new TMDb('2bcff99b7f5691f5a694ce133bcbf715',TMDb::XML);
    $xmlMovieResult = $tmdbXML->getMovie($movieId);
    
    if ($xmlMovieResult == "")
        {
            echo json_encode("Movie not found");
        }
    
    else
        {
            $movies = simplexml_load_string($xmlMovieResult);
            $movie = $movies->movies->movie;
            
            $XMLPath = "..//XML//";
            
            //Make sure weird chars are stripped from the xml movie name
            $strippedXmlMovieName = preg_replace('/[^A-Za-z0-9 ]/', "", $movie->name);
            
            $filename = $XMLPath.$strippedXmlMovieName.'.xml';
            $fp = fopen($filename, 'w');
            fwrite($fp, $xmlMovieResult);
            fclose($fp);
            
            echo json_encode("Movie Added: ".$movie->name);
        }

}
?>

XML Movie Database/PHP/deleteMovie.php

1
2
3
4
5
6
7
8
9
<?php

$XMLPath = "..//XML//";
$filename = html_entity_decode($_POST["movieTitle"]);
$strippedFilename = preg_replace('/[^A-Za-z0-9 ]/', "", $filename);

unlink($XMLPath.$strippedFilename.".xml");

?>

XML Movie Database/PHP/getMovies.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php

//GET XML (MOVIE) FILE NAMES

$xmlDirectory = opendir("..//XML/");

while ($entryName = readdir($xmlDirectory))
    {
        $dirArray[] = $entryName;
    }

closedir($xmlDirectory);
sort($dirArray);

$indexCount = count($dirArray);
$xmlFileNames = array();

for ($i=0; $i < $indexCount; $i++)
{
    if (substr("$dirArray[$i]", 0, 1) != ".")
    {
        $xmlFileNames[] = $dirArray[$i];
    }
}

//GET MOVIE INFO FROM XML//

$numberOfMovies = count($xmlFileNames);
$moviesTitles = array();
$moviesDescriptions = array();
$moviesPosters = array();
$moviesYears = array();
$moviesIMDB = array();
$moviesTrailers = array();

for ($i = 0; $i <= ($numberOfMovies)-1; $i++)
    {
        $movies = simplexml_load_file("..//XML/".$xmlFileNames[$i]."");
        $movie = $movies->movies->movie;
        $moviesTitles[$i] = (string)$movie->name;
        if ($movie->overview == "" || $movie->overview == " ")
            {
                $moviesDescriptions[$i] = "No overview";
            }
        else
            {    
                $moviesDescriptions[$i] = (string)$movie->overview;
            }
        $checkIfImageExists = $movie->xpath('/OpenSearchDescription/movies/movie/images');
        if (count($checkIfImageExists[0]) == 0)
            {
                $moviesPosters[$i] = "img/noPhotoAvailable.png";
            }
        else
            {
                $moviesPosters[$i] = (string)$movie->images->image->attributes()->url;
            }
        if ($movie->released == "")
            {
                $moviesYears[$i] = "Unknown";
            }
        else
            {
                $date = explode("-",$movie->released);
                $moviesYears[$i] = $date[0];
            }
        if ($movie->imdb_id    == "")
            {
                $moviesIMDB[$i] = "na";
            }
        else
            {
                $moviesIMDB[$i] = (string)$movie->imdb_id;
            }
        if ($movie->trailer == "")
            {
                $moviesTrailers[$i] = "na";
            }
        else
            {
                $moviesTrailers[$i] = (string)$movie->trailer;
            }
    }
    
echo json_encode(array("moviesTitles"=>$moviesTitles,"moviesDescriptions"=>$moviesDescriptions,"moviesPosters"=>$moviesPosters,"moviesYears"=>$moviesYears,"moviesIMDB"=>$moviesIMDB,"moviesTrailers"=>$moviesTrailers));

?>

XML Movie Database/PHP/TMDb/TMDb.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
<?php
/**
* TMDb PHP API class - API 'themoviedb.org'
* API Documentation: http://api.themoviedb.org/2.1/
* Documentation and usage in README file
*
* @author Jonas De Smet - Glamorous
* @since 09.11.2009
* @date 04.08.2010
* @copyright Jonas De Smet - Glamorous
* @version 0.9.4
* @license BSD http://www.opensource.org/licenses/bsd-license.php
*/

class TMDb
{
const TMDB = 'Themoviedb.org (TMDb)';
const IMDB = 'The Internet Movie Database (IMDb)';

const JSON = 'json';
const XML = 'xml';
const YAML = 'yaml';

const API_URL = 'http://api.themoviedb.org/2.1/';

const VERSION = '0.9.4';

/**
* The API-key
*
* @var string
*/
private $_apikey;

/**
* The default return format
*
* @var TMDb::JSON or TMDb::XML or TMDb::YAML
*/
private $_format;

/**
* The default language
*
* @var string
*/
private $_lang;

/**
* The available return formats
*
* @var array
*/
private $_formats = array(TMDb::JSON, TMDb::XML, TMDb::YAML);

/**
* Default constructor
*
* @param string $apikey API-key recieved from TMDb
* @param const[optional] $defaultFormat Default return format
* @param string $defaultLang Default language
* @return void
*/
public function __construct($apikey, $defaultFormat = TMDb::JSON, $defaultLang = 'en')
{
$this->setApikey($apikey);
$this->setFormat($defaultFormat);
$this->setLang($defaultLang);
}

/**
* Search a movie by title
*
* @param string $title Title to search after in the TMDb database
* @param const[optional] $format Return format for this function
* @return string
*/
public function searchMovie($title, $format = null)
{
return $this->_makeCall('Movie.search', $title, $format);
}

/**
* Get a movie by TMDb-id or IMDb-id
*
* @param string $id TMDb-id or IMDb-id
* @param const[optional] $type For use with IMDb-id you have to change this parameter to TMDb::IMDB
* @param const[optional] $format Return format for this function
* @return string
*/
public function getMovie($id, $type = TMDb::TMDB, $format = null)
{
if($type == TMDb::IMDB)
{
return $this->_makeCall('Movie.imdbLookup', $id, $format);
}
else
{
return $this->_makeCall('Movie.getInfo', $id, $format);
}
}

/**
* Get a movie by hash
*
* @param string $hash File hash
* @param const[optional] $format Return format for this function
* @return string
*/
public function getMovieByHash($hash, $format = null)
{
return $this->_makeCall('Hash.getInfo', $hash, $format);
}

/**
* Get images by the TMDb-id or IMDb-id
*
* @param string $id Movie TMDb-id or IMDb-id
* @param const[optional] $format Return format for this function
* @return string
*/
public function getImages($id, $format = null)
{
return $this->_makeCall('Movie.getImages', $id, $format);
}

/**
* Search a person by name
*
* @param string $name Name to search after in the TMDb database
* @param const[optional] $format Return format for this function
* @return string
*/
public function searchPerson($name, $format = null)
{
return $this->_makeCall('Person.search', $name, $format);
}

/**
* Get a person by his TMDb-id
*
* @param string $id Persons TMDb-id
* @param const[optional] $format Return format for this function
* @return string
*/
public function getPerson($id, $format = null)
{
return $this->_makeCall('Person.getInfo', $id, $format);
}

/**
* Get a Movie-version by its TMDb-id or IMDB-id
*
* @param string $id Movie TMDb-id or IMDB-id
* @param const[optional] $format Return format for this function
* @return string
*/
public function getMovieVersion($id, $format = null)
{
return $this->_makeCall('Movie.getVersion', $id, $format);
}

/**
* Get multiple Movie-versions by their TMDb-id or IMDB-id
*
* @param array $ids Array with Movie TMDb-id's or IMDB-id's
* @param const[optional] $format Return format for this function
* @return string
*/
public function getMovieVersions(array $ids, $format = null)
{
return $this->_makeCall('Movie.getVersion', implode(',', $ids), $format);
}

/**
* Get a Person-version by its TMDb-id
*
* @param string $id Person TMDb-id
* @param const[optional] $format Return format for this function
* @return string
*/
public function getPersonVersion($id, $format = null)
{
return $this->_makeCall('Person.getVersion', $id, $format);
}

/**
* Get multiple Person-versions by their TMDb-id
*
* @param array $ids Array with Person TMDb-id's
* @param const[optional] $format Return format for this function
* @return string
*/
public function getPersonVersions(array $ids, $format = null)
{
return $this->_makeCall('Person.getVersion', implode(',', $ids), $format);
}

/**
* Makes the call to the API
*
* @param string $function API specific function name for in the URL
* @param string $param Unencoded paramter for in the URL
* @param const $format Return format for this function
* @return string
*/
private function _makeCall($function, $param, $format)
{
$type = (!empty($format))? $format : $this->getFormat();

$url = TMDb::API_URL.$function.'/'.$this->getLang().'/'.$type.'/'.$this->getApikey().'/'.urlencode($param);

if (extension_loaded('curl'))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);

$results = curl_exec($ch);
$headers = curl_getinfo($ch);

$error_number = curl_errno($ch);
$error_message = curl_error($ch);

curl_close($ch);
}
else
{
$results = file_get_contents($url);
}

return (string) $results;
}

/**
* Setter for the default return format
*
* @param const $format
* @return void
*/
public function setFormat($format)
{
if(in_array($format, $this->_formats))
{
$this->_format = $format;
}
else
{
$this->_format = TMDb::JSON;
}
}

/**
* Getter for the default return format
*
* @return const
*/
public function getFormat()
{
return $this->_format;
}

/**
* Setter for the default language
*
* @param string $lang
* @return void
*/
public function setLang($lang)
{
$this->_lang = $lang;
}

/**
* Getter for the default language
*
* @return string
*/
public function getLang()
{
return $this->_lang;
}

/**
* Setter for the API-key
*
* @param string $apikey
* @return void
*/
public function setApikey($apikey)
{
$this->_apikey = (string) $apikey;
}

/**
* Getter for the API-key
*
* @return string
*/
public function getApikey()
{
return $this->_apikey;
}


}
?>

Commentaar

31-03-2011 14:27

Ik snap echt niet waarom je geen database zou gebruiken voor dit soort dingen.
Data beheer in een text bestand is echt iets van 10 jaar geleden misschien.

31-03-2011 16:16

Omdat een XML bestand misschien veel toegankelijker is voor als meer informatie wilt of als je het bijvoorbeeld wilt importeren in een ander film programma.

31-03-2011 18:41

Je hebt je API-key er in laten staan ;)

1
2
3
<?php
$tmdb = new TMDb('2bcff99b7f5691f5a694ce133bcbf715');
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
$xmlDirectory = opendir("..//XML/");

while ($entryName = readdir($xmlDirectory))
    {
        $dirArray[] = $entryName;
    }

closedir($xmlDirectory);
sort($dirArray);

$indexCount = count($dirArray);
$xmlFileNames = array();

for ($i=0; $i < $indexCount; $i++)
{
    if (substr("$dirArray[$i]", 0, 1) != ".")
    {
        $xmlFileNames[] = $dirArray[$i];
    }
}
?>

Dit kan toch in een keer? Scheelt je een loop en een aantal variabelen. In plaats van de for loop was een foreach loop natuurlijk iets handiger geweest.
substr("$dirArray[$i]", 0, 1) is natuurlijk helemaal uit den boze!

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$xmlDirectory = opendir("..//XML/");
$xmlFileNames = array();
while ($entryName = readdir($xmlDirectory))
{
    if (substr($entryName, 0, 1) != ".")
    {
        $xmlFileNames[] = $dirArray[$i];
    }
}
closedir($xmlDirectory);
sort($xmlFileNames);
?>

Ik ben het ook volledig met Lode eens. Een database is voor dit soort doeleinden veel sneller en overzichtelijker.
Persoonlijk zou ik ook het JSON-object dat getMovies.php aanmaakt anders inrichten. Met één object per film met daarin dan de titel, beschrijving enz.

Verder wel leuk script wat demonsteerd wat je met de TMDb API kunt.

Wouter

31-03-2011 21:51

Data beheer in een text bestand is echt iets van 10 jaar geleden misschien.

In tegendeel, hypes als couchdb zijn helemaal hip.

Daarnaast is XML een heel gangbare manier om data op te slaan die niet bijzonder snel benaderd moet kunnen worden en jouw filmdatabase thuis is bij uitstek iets waar je geen databaseserver voor wilt hoeven zetten.

22-08-2011 22:09

Er zijn hiervoor al apps te downloaden die werken onder windows:
- MediaCenterMaster
- Yammm

Deze genereren ook een XML bestand.

Zelf gebruik ik mediacentermaster, omdat yammm volledig in de achtergrond draait en je geen feedback krijgt.

Wat ik laatst heb gedaan is een php script geschreven die plain IDMB text files uitleest en in een database stopt. (http://www.imdb.com/interfaces)

Inloggen wachtwoord vergeten? Aanmelden