0

我正在尝试使用 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>
4

2 回答 2

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 的情况。

于 2016-11-23T02:40:34.597 回答
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
于 2016-11-23T20:23:33.563 回答