file_get_contents(http://roblox.plus:2052/limiteds):无法打开流:连接被拒绝

时间:2016-06-18 16:03:27

标签: php json file-get-contents

当我运行下面的代码时,我收到错误:

  

file_get_contents(http://roblox.plus:2052/limiteds):无法打开   stream:拒绝连接

$file = file_get_contents('http://roblox.plus:2052/limiteds');
$decode = json_decode($file, false);

foreach($decode AS $person) {
    echo $person->name . ": " . $person->lowestPrice . "<br><br>";
}

这是为什么?我可以通过浏览器访问网站。我还尝试了PHP Fiddle上的代码。

在评论之后,我尝试使用cURL - 但是没有显示结果。

$url = 'http://roblox.plus:2052/limiteds';

//  Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Decode
$decode = json_decode($result, false);


foreach($decode AS $person) {
    echo $person->name . ": " . $person->lowestPrice . "<br><br>";
}

1 个答案:

答案 0 :(得分:1)

出于安全原因,许多主机会阻止您从远程URL加载文件。最好使用CURL下载文件的内容。

我尝试如下,它工作正常。

此file_get_contents方法:

<?PHP
    $file = file_get_contents('http://roblox.plus:2052/limiteds');
    $jsond = json_decode($file, true);

    foreach ($jsond['data'] as $vals) {
        echo $name = $vals["name"].' ';
        echo $lowp = $vals["lowestPrice"].'<br>';    
    }
?>

这在CURL方法中:

<?PHP
    $url = 'http://roblox.plus:2052/limiteds';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);
    $result=curl_exec($ch);
    curl_close($ch);

    $decode = json_decode($result, true);

    foreach ($decode['data'] as $vals) {
        echo $name = $vals["name"].' ';
        echo $lowp = $vals["lowestPrice"].'<br>';
    }
?>

或者你可以打开流

<?php
    // Create a stream
    $opts = array(
            'http'=>array(
                    'method'=>"GET",
                    'header'=>"Accept-language: en\r\n" .
                            "Cookie: foo=bar\r\n"
            )
    );

    $context = stream_context_create($opts);

    // Open the file using the HTTP headers set above
    $file = file_get_contents('http://roblox.plus:2052/limiteds', false, $context);
    $jsond = json_decode($file, true);

    foreach ($jsond['data'] as $vals) {
       echo $name = $vals["name"].' ';
       echo $lowp = $vals["lowestPrice"].'<br>';    
    }
?>

所有这3种方法都运行良好

示例输出

Red Baseball Cap 94
Classic ROBLOX Viking Helm 825
The Classic ROBLOX Fedora 30000
Domino Crown 4300000
Princess Hat 585
The Agonizingly Ugly Yellow Baseball Cap 1398
Jester's Cap 1355
Flag 699999
ROBLOX Classic: Wizard's Hat 599
Tornado Hat 1200
Target Hat 345
JJ5x5's White Top Hat 37142
Bucket 3899
Got Milk Visor 2497
Police Sergeants Cap 6000
相关问题