Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

PHP使用fsockopen获取的html内容要如何进行处理?

由于有个内网自定义hosts的接口,我为了避免DNS这一步,就采用了fsockopen的方式访问接口。
不过由于返回值是一串我不太理解的方式,比如:
4d8 {"code":1,"data":{"cate":"u5e7du9ed8u6545u4e8b","title":"u9152u540eu7684u81eau4fe1","content":"u63a8u9500u5458u60f3u4e86u60f3uff0cu4e00u8a00u672au53d1u5730u51fau4e86u5564u9152u9986u300210u5206u949fu540euff0cu4ed6u56deu6765u8fceu6218u3002</p>"}} 0
我不太理解头部类如4d8和尾部0这样的字符是表示什么的?
有没有比较高效的方式只取得大括号中的值。
PS:我目前采用的是笨方法,就是正则获得花括号中的值。

代码实现如下:

function remote_visit($ip, $host, $port, $url, $timeout){

    $errno = '';
    $errstr = '';

    $fp = fsockopen($ip, $port, $errno, $errstr, $timeout);

    if(!$fp){ // connect fail
        return false;
    }

    $out = "GET ${url} HTTP/1.1
";
    $out .= "Host: ${host}
";
    $out .= "Connection: close

";
    fputs($fp, $out);

    $response = '';

    // 读取内容
    while($row=fread($fp, 4096)){
        $response .= $row;
    }

    fclose($fp);

    $pos = strpos($response, "

");
    $response = substr($response, $pos+4);

//我现在采用了正则的方式取得里面的json部分,如下两行代码
    preg_match('@{(.*?)}@si',$response,$match);
    $response = '{'.$match[1].'}}';
    return $response;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...