v2.5.2
Giriş yap

Wikipedia verilerini PHP ile çekmek ve echo ile göstermek

erdal42
469 defa görüntülendi ve 1 kişi tarafından değerlendirildi

Merhabalar
Wikipedia : https://www.mediawiki.org/wiki/API:Main_page
Bu api ile nasıl php ile çekerim. Resimli ve başlıklı almak istiyorum.
Nasıl yaparız ?

etukenmez
859 gün önce

Şöyle bir kod yazdım açıklamaları ekledim liste şeklinde verileri çekiyor.


//Aramak istediğimiz değer
$searchParam = "Test";

$searchTitle = [
    "action" => "query",
    "list" => "search",
    "srsearch" => $searchParam,
    "format" => "json",
    /* Bu değerler kullanılarak sayfalama yapılabilir */
//    "srlimit" => 10,
//    "sroffset" => 9
];

/* verileri çekecek olan metodumuz */
function getData($params){
    $endPoint = "https://en.wikipedia.org/w/api.php";
    $url = $endPoint . "?" . http_build_query( $params );

    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    $output = curl_exec( $ch );
    curl_close( $ch );

    return json_decode( $output, true );
}

echo '<ul>';
$result = getData($searchTitle);

$query = $result['query'];
$total = $query['searchinfo']['totalhits'];
$datas = $query['search'];
/* Sonuç var mı kontrolü */
if ($total){
    foreach ($datas as $data){
        /* görselleri çekmek için belirteceğimiz parametreler */
        $imagesParam = [
            "action" => "query",
            "prop" => "images",
            "titles" => $data['title'],
            "format" => "json",
        ];

        echo '<li>';
        $images = getData($imagesParam);
        $firstPage = reset($images['query']['pages']);
        /* Konuya ait görsel değeri döndümü kontrolü yapılıyor */
        if ($firstPage && count($firstPage['images']) > 0){
            $imageUrlParams = [
                "action" => "query",
                "format" => "json",
                "prop" => "imageinfo",
                // İlk görseli alıyoruz
                "titles" => $firstPage['images'][0]['title'],
                'iiprop' => 'url'
            ];
            /* Görselin detayını çekerek url değerini bulmak için istek atıyoruz */
            $imageUrlResponse = getData($imageUrlParams);
            $imageUrlResponseFirstPage = reset($imageUrlResponse['query']['pages']);
            /* Dönen değer var mı kontrolü */
            if ($imageUrlResponseFirstPage && count($imageUrlResponseFirstPage['imageinfo']) > 0)
                echo '<img width="32" src="'. $imageUrlResponseFirstPage['imageinfo'][0]['url'] .'">';
        }

        echo $data['title'];
        echo '</li>';
    }
}else{
    echo $searchParam . ' hakkında hiç içerik bulunamadı';
}
echo '</ul>';

HTML tarafında bir input ve button koyarak yazılan değeri bu kod parçasıyla kullanırsan aramalar görselleriyle beraber liste şeklinde görünür.