Reputation: 453
Hi could someone point out and explain where I am going wrong in trying to retrieve data from Wikipedia based on a user's search? Please see the code below. Thanks.
<html>
<head></head>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" />
</form>
<?php
// if form submitted
if (isset($_POST['q'])) {
$search = $_POST['q'];
$url = "http://en.wikipedia.org/w/api.php?
action=query&list=search&srwhat=text&format=json&srsearch={$search}&continue=";
$res = file_get_contents($url);
$data = json_decode($res);
?>
<h2>Search results for '<?php echo $_POST['q']; ?>'</h2>
<ol>
<?php foreach ($data->query->search as $r): ?>
<li><a href="http://www.wikipedia.org/wiki/
<?php echo $r['title']; ?>">
<?php echo $r['title']; ?></a> <br/>
<small><?php echo $r['snippet']; ?></small></li>
<?php endforeach; ?>
</ol>
<?php
}
?>
</body>
</html>
Upvotes: 0
Views: 76
Reputation: 9476
Try following updated code:
<html>
<head></head>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" />
</form>
<?php
// if form submitted
if (isset($_POST['q'])) {
$search = $_POST['q'];
$url = "http://en.wikipedia.org/w/api.php?action=query&list=search&srwhat=text&format=json&srsearch=$search&continue=";
$res = file_get_contents($url);
$data = json_decode($res);
echo "<pre>";
print_r($data);
echo "</pre>";exit;
?>
<h2>Search results for '<?php echo $_POST['q']; ?>'</h2>
<ol>
<?php foreach ($data->query->search as $r): ?>
<li><a href="http://www.wikipedia.org/wiki/
<?php echo $r->title; ?>">
<?php echo $r->title; ?></a> <br/>
<small><?php echo $r->snippet; ?></small></li>
<?php endforeach; ?>
</ol>
<?php
}
?>
</body>
</html>
Upvotes: 1
Reputation: 1
Please remove space before "action" in url
$url = "http://en.wikipedia.org/w/api.php? action=query&list=search&srwhat=text&format=json&srsearch={$search}&continue=";
Should Be
$url = "http://en.wikipedia.org/w/api.php?action=query&list=search&srwhat=text&format=json&srsearch={$search}&continue="; You can also use urlencode.
Upvotes: 0