0

I'm trying to get some data from a wikipedia API but i am receiving this message.

Here is the PHP script with the small html form above:

    <form action="" method="get">
    <input type="text" name="busca">
    <input type="submit" value="Busca">
</form>

<?php

    if($_GET['busca']){
        $api_url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&titles=".ucwords($_GET['busca']).".redirects=true";
        $api_url = str_replace(' ', '%20', $api_url);

        if($data = json_decode(file_get_contents($api_url))){
            foreach($data->query->pages as $key=>$val){
                $pageId = $key;
                break;
            }
            $content = $data->query->pages->$pageId->extract;

            header('Content-Type:text/html; charset=utf-8');
            echo $content;
        }
        else{
            echo 'Nenhum resultado encontrado.';
        }
    }
?>

So i get:

Notice: Undefined property: stdClass::$extract in C:\xampp\htdocs\wiki\index.php on line 18

the_piper
  • 105
  • 2
  • 12

1 Answers1

0

You have an issue with your $api_url. In the end there is .redirects=true and it should actually be ?redirects=true

Also, you are indeed using classes, in PHP when you use -> that means you are trying to access an object property or function. So you are accessing attribute query of object $data, and than pages of object $data->query and then $pageId of object $data->query->pages and than extractor of object $data->query->pages->$pageId.

If for some reason it doesnt have the attribute you are trying to get you will see that notice.

I highly recommend you to be sure of the structure you are receiving to make sure you dont need to check if other parts of this structure are present and what to do when they are not.

If you are sure that extractor is the only part of your structure that might not be present in some scenarios you can check if that property exists first and than do something if it is not there.

$content = '';
if (isset($data->query->pages->$pageId->extract)) {
     $content = $data->query->pages->$pageId->extract
}

More info on the isset() function https://www.php.net/manual/en/function.isset.php

Murilo
  • 580
  • 5
  • 21
  • yeah, seems 'extract' doesn't exist. I removed the attribute and I'm trying to get the result from $content with print_r($content) and now, it gives me: stdClass Object ( [ns] => 0 [title] => Nepal.redirects=true [missing] => ) – the_piper Nov 26 '19 at 14:47
  • You have an issue with your `$api_url`. In the end there is `.redirects=true` and it should actually be `?redirects=true` – Murilo Nov 27 '19 at 04:40