Faraz Anwer
Faraz Anwer

Reputation: 31

Fetching Images of places from wikipedia

I'm Using the following code to fetch images from wikipedia api but at the moment it is giving me random images on that keyword like if I search "spain " it will give me random images with word spain but I need the images of places in spain like we get in wikipedia. Can any one help me with that?

<form action="" method="get">
    <input type="text" name="search">
    
    <input type="submit" value="Search">
</form>

<?php
if(@$_GET['search']){
    function get_wiki_image( $search, $limit) {

  $streamContext = array(
    "ssl" => array(
          "verify_peer" => false,
          "verify_peer_name" => false,
      ),
  );

  $url = 'https://en.wikipedia.org/w/';
  $url .= '/api.php?action=query&format=json&list=allimages&aifrom=' . $search . '&ailimit=' . $limit;

  $context = stream_context_create($streamContext);

  if(FALSE === ($content = @file_get_contents($url, false,$context)) ) {
    return false;
  } else {
    $data = json_decode($content,true);
    $ret = array();
    foreach($data['query']['allimages'] as $img) {
      $ret[] = $img['url'];
    }
    return $ret;
  }

}

$search = ucwords($_GET['search']);
$images = get_wiki_image($search,500);

foreach($images as $img) {
  echo "<img src='{$img}' height='50' width='50'>";
}

}



?>

Upvotes: 0

Views: 141

Answers (1)

Pascalco
Pascalco

Reputation: 2826

You can use the PageImages API for this purpose. Generally, it returns you the first image in an article, however, depending on the configurations of Wikipedia it might return a different image in some cases.

To get for example the image of the "Barcelona" article, call https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Barcelona&piprop=original.

If you need the picture in a certain size, you can also call https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Barcelona&pithumbsize=250.

Upvotes: 1

Related Questions