繁体   English   中英

使用PHP从URL获取数据

[英]Getting data from url using PHP

我正在尝试搜索Wikipedia,并在php中获得结果。 当我在php文件中将URL作为硬编码字符串输入url时,它可以工作,但是如果我尝试将url作为参数输入,它将返回以下内容:

["",[],[],[]]

这是带有硬编码字符串的代码:

<?php
$opts = array('http' =>
  array(
    'user_agent' => 'User1 (http://www.exampe.com/)'
  )
);
$context = stream_context_create($opts);
$url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=yolo';
echo file_get_contents($url, FALSE, $context);
?>

以下是从其网址获取参数的版本:

<?php
$opts = array('http' =>
  array(
    'user_agent' => 'User1 (http://www.exampe.com/)'
  )
);
$context = stream_context_create($opts);
$url = $_GET['url'];
echo file_get_contents($url, FALSE, $context);
?>

这是我输入参数的方式:

http://example.com/test.php?url=http://en.wikipedia.org/w/api.php?action=opensearch&search=yolo

发生问题是因为您的get参数包含具有特殊含义的字符,例如%,?,/ 、:和=。

解决方案:

  • 用%26替换&
  • 用%2F替换/
  • 用%3A代替
  • 取代? 按%3F
  • 用%3D替换=

还有更多需要替换的字符,但是这些字符不会出现在您的URL中。

您的网址将变为

http://example.com/test.php?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Fapi.php%3Faction%3Dopensearch%26search%3Dyolo

您可以使用php函数urlencode轻松完成此操作

您必须先对查询字符串进行编码,然后再提交

http://example.com/test.php?url=http://en.wikipedia.org/w/api.php?action=opensearch&search=yolo

http://example.com/test.php?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Fapi.php%3Faction%3Dopensearch%26search%3Dyolo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM