检索维基百科数据

时间:2014-11-10 09:33:01

标签: php json

嗨,有人可以指出并解释我在尝试根据用户搜索从维基百科检索数据时出错吗?请参阅下面的代码。谢谢。

<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>

2 个答案:

答案 0 :(得分:1)

尝试使用以下更新代码:

<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>

答案 1 :(得分:0)

请删除网址“action”之前的空格

$ url =“http://en.wikipedia.org/w/api.php? 行动=查询&安培;列表=搜索&安培; srwhat =文本&安培;格式= JSON&安培; srsearch = {$搜索}&安培;继续=“;

应该

$ url =“http://en.wikipedia.org/w/api.php?action=query&list=search&srwhat=text&format=json&srsearch= {$ search}&amp; continue =”; 你也可以使用urlencode。