使用Google API PHP SDK调用InspectUrlIndexRequest出现未定义调用错误
解决SearchConsole API调用inspect函数时的Undefined property错误
错误原因
你代码中调用的$service->index不存在,Google\Service\SearchConsole类中没有名为index的成员属性,正确的API资源标识是urlInspection_index(对应Search Console API的urlInspection.index端点)。
修正后的代码
use Google\Client; use Google\Service\SearchConsole; use Google\Service\SearchConsole\InspectUrlIndexRequest; $client = new Client(); $client->setAuthConfig(PATH_TO_CREDS); // 注意原代码中PATHT/TO/CREDS为拼写错误,需修正为正确路径 $client->setApplicationName(NAME); $client->addScope("https://www.googleapis.com/auth/webmasters.readonly"); $client->authenticate($accessToken); $service = new SearchConsole($client); $queryRequest = new InspectUrlIndexRequest(); $queryRequest->setInspectionUrl(URL); $queryRequest->setSiteUrl(SITE_URL); // 原代码中SITE URL需改为合法变量名或直接传入字符串 // 修正后的正确调用方式 $response = $service->urlInspection_index->inspect($queryRequest);
额外注意事项
- 确保引入了正确的命名空间,避免因类名找不到引发错误
- 检查
PATH_TO_CREDS、NAME、URL、SITE_URL这些变量是否已正确定义或替换为实际值
内容的提问来源于stack exchange,提问作者user18245606
相关产品推荐
相关产品推荐

