【问题标题】:Reading data from socket从套接字读取数据
【发布时间】:2014-06-07 00:08:59
【问题描述】:

我希望我的代码返回:

  • ISP:EdgeCast 网络

  • 国家:美国

但是使用这段代码,我只能得到一行,而不是全部。 如何在不同的行中获取此信息?

$ip="/locator/ip-lookup.php?ip=93.184.216.119";
$ISP='/<th>ISP:<\/th><td>(.+)<\/td>/';
$country="/<th>Country:<\/th><td>\s(.+)*$/";    
$fp = fsockopen("www.ip-tracker.org", 80, $errno, $errstr, 30);

if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} 
else {
    $out = "GET $ip HTTP/1.1\r\n";
    $out .= "Host: www.ip-tracker.org\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);

    while (!feof($fp)) {
        if (preg_match($ISP,fgets($fp,128),$matches)) {
            echo "ISP: ".$matches[1]. "<br>";
        }
        if (preg_match($country,fgets($fp,128),$matches)) {
          echo "Country: ".$matches[1]. "<br>";
        }
    }

【问题讨论】:

  • 你目前得到的输出是什么?
  • 请将您的代码简化为最小示例。我想整个套接字问题与真正的问题无关,是吗?
  • 我不知道如何把它放在最小的例子中,它只有一行输出,而不是两行
  • 如果它返回这个:ISP: EdgeCast Networks 你为什么会有这个:&lt;th&gt;ISP:&lt;\/th&gt;&lt;td&gt;(.+)&lt;\/td&gt;。这根本没有意义。
  • @user7874:您正在尝试解析 HTML。使用 DOM 解析器而不是正则表达式。 (谷歌搜索“php domdocument 示例”应该可以帮助您入门)

标签: php regex sockets


【解决方案1】:
<?
$html = file_get_contents("http://www.ip-tracker.org/locator/ip-lookup.php?ip=93.184.216.119");

preg_match_all('%Country:</th><td> (.*?) &nbsp;.*?<th>ISP:</th><td>(.*?)</td>%sm', $html, $result, PREG_PATTERN_ORDER);
$country = $result[1][0];
$isp = $result[2][0];

echo $country; // United States
echo $isp; // EdgeCast Networks
?>

【讨论】:

  • 谢谢老兄,这正是我想要的,不知道在这种情况下我可以使用 file_get_contents 和 preg_match_all
  • %sm 是什么意思?
  • s -> 点匹配换行符; m -> ^ 和 $ 在换行符处匹配
猜你喜欢
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-10
相关资源
最近更新 更多