PHP - 奇怪的file_get_contents行为

时间:2017-09-08 09:33:49

标签: php file-get-contents behavior

当我运行第一个代码时,它运行良好。回声有效。

<?php
$html = file_get_contents('https://feedback.aliexpress.com/display/productEvaluation.htm?productId=32795887882&ownerMemberId=230515078&withPictures=true&i18n=true&Page=3'); 
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
echo $image->getAttribute('src');
echo "<br>";
}
?>

但是,当我尝试使用以下代码并使用参数运行时,不会返回任何内容:

的index.php?URL = https://feedback.aliexpress.com/display/productEvaluation.htm?productId=32795887882&ownerMemberId=230515078&withPictures=true&i18n=true&Page=3

<?php

$html = file_get_contents($_GET["url"]);
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
echo $image->getAttribute('src');
echo "<br>";
}
?>

有人有任何想法吗?

更新

原来不是最好,最干净的解决方案,但它可以工作:)

<?
$url = urldecode($_GET['url']);
$ownerMemberId = urldecode($_GET['ownerMemberId']);
$withPictures = urldecode($_GET['withPictures']);
$page = urldecode($_GET['Page']);

$newurl = $url . "&ownerMemberId=" . $ownerMemberId . 
"&withPictures=true&i18n=true&Page=" . $page;

$html = file_get_contents($newurl);
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {
echo "<img src='";
echo $image->getAttribute('src');
echo "'>";
echo "<br>";
}

?>

1 个答案:

答案 0 :(得分:4)

请在发送其他网址时解码网址。

$url = urldecode($_GET['url']);
$html = file_get_contents($url);
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {
    echo $image->getAttribute('src');
    echo "<br>";
}

希望对你有用。