Monatsarchiv für May 2011

 
 

MediaWiki Api

Here is an example of how to start using the MediaWiki Api. For demo purposes I’m getting data from Wikipedia:

First we need some php for the http request. You need to send a user agent value that contains contact information, otherwise MediaWiki will not let you access any data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
 
  $defaults = array(
    "term" => "water", 
    "limit" => "10"  
  );
 
  foreach($defaults as $key => $value){
    if (isset($_REQUEST[$key])){
     $defaults[$key] =  urlencode($_REQUEST[$key]);
    }
  }
 
  ini_set("user_agent", "Demo for http://zreference.com/");
 
  echo file_get_contents("http://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={$defaults['term']}&srlimit={$defaults['limit']}&format=xml");

Then we can use a little jQuery to load and display the data:

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
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>MediaWiki Api</title>
    <script src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
    <script>
 
      $(function(){
 
        var body = $("body");
 
        var vars = {
          term : "strange attractor",
          limit : 10,
        }
 
        $.post("wiki.php", vars, function(data){
          var parsed = $.parseXML(data);
          var results = $(parsed);
 
          results.find("p").each(function(){
            var curr = $(this);
            var title = curr.attr("title");
            var link = "http://en.wikipedia.com/wiki/" + title;
            var content = "<h1>" + title +"<\/h1>";
            content += curr.attr("snippet");
            $("<div/>", {
              html : content,
              className : "result"
            }).appendTo(body)
              .wrap("<a href='"+link+"' target='_blank'/>");
          });
 
        });
 
      });
    </script>
    <style>
      a{
        text-decoration : none;
        color : black; 
        -webkit-transition : color 0.5s;
      }
      a:hover{
        color : red; 
      }
      .result{
        position : relative;
        font-family : sans-serif; 
        margin-bottom : 10px;
      }
      .result h1{
        font-size : 20px; 
      }
    </style>
    <body>
    </body>
  </head>
</html>

Rather than using jQuery.animate() I decided to use a css webkit transition for the rollover – just for demo purposes.

There’s lots of documentation for this api – there is a nice summary if you visit api.php:

http://en.wikipedia.org/w/api.php

The final result will look like this.