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