如何通过Google API获取索引状态?调试返回数据格式调整需求
Extract Date & Indexed Count from
Google_Service_Webmasters_SitemapsListResponse Got it, let's break down how to convert that response object into the array you need with dates and indexed values. Here's a straightforward, step-by-step solution:
Step 1: Pull Raw Model Data from the Response
First, grab the underlying associative array data from the response object. Using the official getModelData() method is the most reliable approach (it works consistently across different versions of the Google Client Library):
// Your existing sitemap list request $sitemapResponse = $sitemaps->listSitemaps("http://example.com", ['contents' => 'indexed']); // Extract the raw model data as an associative array $modelData = $sitemapResponse->getModelData();
Step 2: Parse Entries into Your Target Array
Next, loop through each sitemap entry in the sitemaps property of the model data. For each entry, extract the submission date and the indexed page count:
// Initialize your final result array $indexStatusArray = []; foreach ($modelData['sitemaps'] as $sitemap) { // Format the last submitted date (adjust the date string to your preferred format) $formattedDate = date('Y-m-d', strtotime($sitemap['lastSubmitted'])); // Retrieve the indexed page count from the contents array $indexedCount = 0; foreach ($sitemap['contents'] as $content) { if ($content['type'] === 'indexed') { $indexedCount = $content['count']; break; // Exit early once we find the indexed entry } } // Add the parsed data to your result array $indexStatusArray[] = [ 'date' => $formattedDate, 'indexed_pages' => $indexedCount ]; }
Step 3: Use the Final Array
Your $indexStatusArray will now be structured exactly as you need it, like this:
[ ['date' => '2024-05-20', 'indexed_pages' => 456], ['date' => '2024-05-15', 'indexed_pages' => 321], // ... additional sitemap entries ]
Quick Notes:
- If you want to keep Google's original ISO 8601 date format, skip the
date()andstrtotime()calls and use$sitemap['lastSubmitted']directly. - The safeguard check for the
indexedcontent type ensures your code handles edge cases, even though you specified['contents' => 'indexed']in your request.
内容的提问来源于stack exchange,提问作者Luiz Carlos Pedroso Gomes
相关产品推荐
相关产品推荐

