Using fopen twice

こ雲淡風輕ζ 提交于 2019-12-12 06:02:12

问题


I would like to open 2 url's using open

$url = 'http://xtreme-jumps.eu/demos.txt';
$url2 = 'http://cosy-climbing.net/demoz.txt';

Something like this... but it's not working

$handle = @fopen($url, "r");
$handle .= @fopen($url2, "r");

I need to join them because later i'll search there

if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $map) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

Thanks


回答1:


You could try something like this:

$handles=array();

$handles[]=@fopen($url, "r");
$handles[]=@fopen($url2, "r");

foreach($handles as $handle){
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $map) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);

}

or better:

$urls=array(
    'http://xtreme-jumps.eu/demos.txt',
    'http://cosy-climbing.net/demoz.txt'
);


foreach($urls as $url){
    $handle=@fopen($url, "r");
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $map) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);

}



回答2:


You can't concatenate handles. You need to use fread() (or just file_get_contents()) if you want the actual file contents.




回答3:


Well, no, that won't work because handle is a resource, not the contents of the web page you're trying to open.

If you want to join the content together, you need to open the first URL, get the content, open the second and get the content, then join the content.

You can reuse handle for the second open if you finish all your operations on the first but you can't have a single handle connected to two URLs at the same time. You certainly can't do that by attempting to concatenate them.

If you want to access the two URLs concurrently, just use two different resource handles.




回答4:


Perhaps you want file_get_contents() instead? fopen returns a resource handle, which you later use to read (or write) to.



来源:https://stackoverflow.com/questions/9865434/using-fopen-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!