Wordnik"试图获得非对象的属性"尝试getDefinitions时出错

时间:2016-11-23 02:31:54

标签: php html api wordnik

我试图使用Wordnik PHP API,但我遇到了一些麻烦。我尝试使用getDefinitions方法,但它返回错误:Notice: Trying to get property of non-object in C:\xampp\htdocs\index.php on line 18

以下是代码:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form method="post">
            <input type="text" placeholder="First Word" name="word1">
            <input type="submit" placeholder="Compare">
        </form>
        <?php
            require('./wordnik/Swagger.php');
            $APIKey = '342eac9900e703079b0050d5f7008eab962195189e75bfbcb';
            $client = new APIClient($APIKey, 'http://api.wordnik.com/v4');

            $word1 = $_POST['word1'];
            $wordApi = new WordApi($client);
            $word1 = $wordApi->getDefinitions($word1, null, null);
            print $word1->text;
        ?>
    </body>
</html>

2 个答案:

答案 0 :(得分:1)

我认为你的通知(不是真正的php世界中的错误)不是来自$word1 = $wordApi->getDefinitions($word1, null, null);,而是来自print $word1->text;是否可能?

如果您查看WorldApi类:

https://github.com/wordnik/wordnik-php/blob/master/wordnik/WordApi.php#L182 https://github.com/wordnik/wordnik-php/blob/master/wordnik/WordApi.php#L138

您可以看到getDefinitions(...)返回Definition数组或null。

有一件事是肯定的,如果返回有效,则无法从->text获取$word1属性,而是从其中一个索引获取。试试$word1[0]->text

无论如何,你还应该处理getDefinitions(...)的返回返回一个空数组或null的情况。

答案 1 :(得分:0)

此示例代码可能会对您有所帮助:

apiUrl = 'http://api.wordnik.com/v4'
apiKey = 'YOURKEYHERE'
client = swagger.ApiClient(apiKey, apiUrl)
wordApi = WordApi.WordApi(client)
res = wordApi.getWord('cat')
res2 = wordApi.getDefinitions('cat')
assert res, 'null getWord result'
assert res.word == 'cat', 'word should be "cat"'
print res.word
print dir(res2[0])
print res2[0].partOfSpeech