-1

I am getting Undefined index error. I saw a similar type of question in the same site. I am unable to fix this error can anyone help me

    <?php
   if (isset($_GET['query']) && $_GET['query'] != '') {

$url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI';
 

$query_fields = ['autoCorrect' => 'true',
          
          'pageNumber' => 1,

          'pageSize' => 10,

          'safeSearch' => 'false',

          'q' => $_GET['query']
  ];

  $curl = curl_init($url . '?' . http_build_query($query_fields));
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, [
          'X-RapidAPI-Host: contextualwebsearch-websearch-v1.p.rapidapi.com',
          'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  ]);
  $response = json_decode(curl_exec($curl), true);
  curl_close($curl);

  $news = $response['value']; //Error get in this line
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>News Searcher</title>
</head>
<body>
  <form action="new2.php" method="GET">
          <label for="query">Enter your query string:</label>
          <input id="query" type="text" name="query" />
          <br />
          <button type="submit" name="submit">Search</button>
  </form>
  <br />

<?php
  if (!empty($news)) {
          echo '<b>News by Your query:</b>';
          foreach ($news as $post) {
             echo '<h3>' . $post['title'] . '</h3>';
             echo '<a href="' . $post['url'] . '">Source</a>';
             echo '<p>Date Published: ' . $post['datePublished'] . '</p>';
             echo '<p>' . $post['body'] .'</p>';
             echo '<hr>';
          }
  }
?>
</body>
</html>
aynber
  • 22,380
  • 8
  • 50
  • 63
  • 2
    Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – El_Vanja Mar 22 '21 at 14:49
  • Dump the response to see what you're actually getting. – El_Vanja Mar 22 '21 at 14:50
  • my code is different – SHIVANAND RASKONDA Mar 22 '21 at 15:03
  • 2
    Your code being different doesn't matter - the issue is the same. `$response` doesn't have a `value` index. We can't know what you're getting from your cURL request - only you can check that. – El_Vanja Mar 22 '21 at 15:06

1 Answers1

0

This error is occurring because the parameter value does not exist in the response array. To debug correctly and check the response return, you must use the var_dump($ response) command and check the actual returns.

David Dutra
  • 391
  • 7
  • 21