开发者

Convert Java Code To PHP - URL Connections and Reading Response

开发者 https://www.devze.com 2023-03-30 20:35 出处:网络
I wrote the following Java program to connect google.com, get its HTML source code in return, print the entire source code on the screen and then count the no. of line breaks (<br>) in the code.

I wrote the following Java program to connect google.com, get its HTML source code in return, print the entire source code on the screen and then count the no. of line breaks (<br>) in the code. It is working fine.

String QUERY = "http://www.google.com";

URL url = new URL(QUERY);

URLConnection connection = url.openConnection();

connection.setDoInput(true);

InputStream inStream = connection.getInputStream();

BufferedReader input = new BufferedReader(new InputStreamReader(inStream));

String line = "";

int count = 0;

while ((line = input.readLine()) != null)

   {

   System.out.println(line);

   if(line.contains("br"))

      {

      count++;

      System.out.println(count);

      }

   }

The problem is, i want to write a similar code in PHP. I know that URL's can be called using fope开发者_JAVA百科n, and read into a String type variable using fread.

I want to know how i can print it (maybe echo?). But more importantly, how can i search for a desired string in the source code, and not just count the no. of occurences, but also retrieve a string/set of characters after the specified search-string's location.


It's a little bit of strange request and you seem to be printing the numbers after you print each lone (and not at the end). Also you seem to be counting every line that contrains a br just once but this should get you started for php:

<?php
$count = 0;
foreach(file("http://www.google.com") as $line) {
    echo $line, PHP_EOL;
    if(strpos('br', $line)) { 
        ++$count;
    echo $count, PHP_EOL;
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消