简体   繁体   中英

I am getting “Notice: Undefined property: stdClass”

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM