PHP处理file_get_contents错误

时间:2015-04-26 18:24:28

标签: php

所以下面的代码中发生的是我在这个链接上从游戏中获取高分数据:     http://hiscore.runescape.com/index_lite.ws?player=

在网址末尾使用正确的用户名时,一切正常,例如" n0tch"。但是当用户名不存在时,它会显示游戏的网站。我需要的是一种检查页面上是否存在字符串的方法。

我收到错误:

为了帮助您更好地理解,我会尝试将这些网址输入您的浏览器:

现有&工作用户名:

http://hiscore.runescape.com/index_lite.ws?player=n0tch

不存在&在PHP中调用时抛出错误:

http://hiscore.runescape.com/index_lite.ws?player=asdfse123d

我需要在foreach循环周围添加一些错误检查语句。目前我正在尝试获取网站的响应代码,但每次都是200.

代码:

<?php
  $rsn=$_GET["rsn"]; 
  $stats=array("Overall","Attack","Defence","Strength","Hitpoints","Ranged","Prayer","Magic","Cooking","Woodcutting","Fletching","Fishing","Firemaking","Crafting","Smithing","Mining","Herblore","Agility","Thieving","Slayer","Farming","Runecrafting","Hunter","Construction","Summoning","Dungeoneering","Duel Tournament","Bounty Hunters","Bounty Hunters Rougue","Fist Of Guthix","Mobilising Armies");
  $url="http://hiscore.runescape.com/index_lite.ws?player=".$rsn; 

  $a="0";

  echo "<pre>Showing Stats for: ".$rsn."\r\n"; 
  echo "<center>
  <table>
  <tr>
  <th>Skill</th>
  <th>Rank</th>
  <th>Level</th>
  <th>Experience</th>
  </tr>";
 // var_dump($http_response_header);



   var_dump(http_response_code());


  if (http_response_code(200)) {
    $data=explode(chr(10),file_get_contents($url));
    foreach ($data as $value) { 
      if ($a<26) {  
        $value=str_replace(",","</td><td>",$value);
        $pic = "<img class='img-resize' src='./img/skills/".$stats[$a].".png'>";
        echo "<tr><td id='firstRow'>".$pic."&nbsp;".$stats[$a].":</td> ".str_replace("-1 -1","Not Ranked",str_replace("-1 -1 -1","Not Ranked","<td>".$value."</td></tr>"))."\r\n";
      }
      $a++; 
    } 
    echo "</table></center>";
    echo "Done";
  } else {
    echo "didn't work";
  }
?>

2 个答案:

答案 0 :(得分:1)

这是因为给出了不同的结构。当付款人存在时,您会得到一些带有数字的空白页面,如果不存在,服务器将返回404响应并重定向。所以你必须确保在爆炸之前从服务器获得什么内容。添加一些验证并尝试catch块。要么使用curl。

答案 1 :(得分:1)

以下是通过$rsn=$_GET["rsn"]; $url="http://hiscore.runescape.com/index_lite.ws?player=".$rsn; if(getHeadersCheck($url)) { $data=explode(chr(10),file_get_contents($url)); } else $data = null; if($data === null) echo 'Sorry, can\'t display results'; else if (is_array($data)) { $stats = '(Whatever stats should represent.. )'; foreach($data as $value) { // Do whatever You want to do.. } }

检查响应标头的简单函数
[usernamehere]
secret=yourpasswordhere
deny=0.0.0.0/0.0.0.0
permit=204.0.0.1/255.255.255.255
read=all,system,call,log,verbose,command,agent,user,originate
;write=command,call,originate
displayconnects=yes

以下是您的代码与此函数的相似之处......

abc123