使用 PHP 从 url 获取数据

Getting data from url using PHP

我正在尝试搜索维基百科并在 php 中获得结果。当我在 php 文件中输入 url 作为硬编码字符串时它起作用,但是如果我尝试将 url 作为参数它 returns this:

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

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

<?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);
?>

这是从其 url 中获取参数的版本:

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

您必须在提交之前对查询字符串进行编码

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

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

解决方法:

  • 将 & 替换为 %26
  • 将 / 替换为 %2F
  • 替换:由 %3A
  • 替换?通过 %3F
  • 将 = 替换为 %3D

还有更多字符需要替换,但在您的 URL 中没有出现。

你的URL然后变成

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

您可以使用 php 函数轻松做到这一点 urlencode