【问题】
写了几行PHP代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /** * add newline for print */ function printAutoNewline( $contentToPrint ) { print_r( $contentToPrint . "<br />" ); } /** * get url reponse html */ function getUrlRespHtml( $url ) { printAutoNewline( "input url=" . $url ); $respHtml = "" ; //resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] ) $res = fsockopen ( $url ); printAutoNewline( $res ); return $respHtml ; } $yesllRespHtml = getUrlRespHtml( $yellEntryUrl ); printAutoNewline( "yesllRespHtml=" . $yesllRespHtml ); |
结果运行出错:
Warning: fsockopen() [function.fsockopen]: unable to connect to http://www.yell.com/:-1 (Unable to find the socket transport "http" – did you forget to enable it when you configured PHP?) in xxx.php on line 27 |
【解决过程】
1. 参考了:
fsock: Unable to find the socket transport “http”
看到其解释说fsockopen不支持Laye5+,所以不能直接给url地址,而只能给ip地址。
然后其建议用curl extension。
2.所以去找找php的curl extension。
然后找到:
好像是用其实现url的访问,很是麻烦,需要类似于这样的代码:
1 2 3 4 5 6 7 8 | $ch = curl_init(); curl_setopt( $ch , CURLOPT_URL, $url ); curl_setopt( $ch , CURLOPT_HEADER, TRUE); curl_setopt( $ch , CURLOPT_NOBODY, TRUE); // remove body curl_setopt( $ch , CURLOPT_RETURNTRANSFER, TRUE); $head = curl_exec( $ch ); $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE); curl_close( $ch ); |
3.重新参考官网的解释:
去把代码改改为:
1 | $fp = fsockopen ( $url , 80); |
结果还是同样错误:
Warning: fsockopen() [function.fsockopen]: unable to connect to http://www.yell.com/:80 (Unable to find the socket transport "http" – did you forget to enable it when you configured PHP?) in xxx.php on line 27 |
4.把代码改为:
1 2 | $testHostname = "www.yell.com" ; $fp = fsockopen ( $testHostname , 80); |
然后就可以了。
然后可以看到打印输出了:
Resource id #2 |
【总结】
把对应的url地址:
改为
xxx.xxx.com
然后再去调用fsockopen,记得port设置为80(默认是-1),就可以正常访问了:
1 2 | $testHostname = "www.yell.com" ; $fp = fsockopen ( $testHostname , 80); |
总之,使用fsockopen去获得网页内容,极其的不方便。还是尽量去想别的办法去获得网页内容吧。
转载请注明:在路上 » 【已解决】PHP代码运行出错:Warning: fsockopen() [function.fsockopen]: unable to connect to xxx:-1 (Unable to find the socket transport "http" – did you forget to enable it when you configured PHP?) in xxx.php on line xx