0

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 fopen, 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.

durron597
  • 31,968
  • 17
  • 99
  • 158
Nibhrit
  • 188
  • 1
  • 2
  • 14

1 Answers1

2

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;
    }

}
edorian
  • 38,542
  • 15
  • 125
  • 143
  • Thanks, it does get me started...though barely.When i run this code, my browser opens Google, rather than retrieving its HTML and echoing the 'count'. – Nibhrit Aug 25 '11 at 08:42
  • 1
    Well no. It just prints the contents of www.google.com line by line and if you call that in a browser (the java version seems to be called on the cli so i thought you'd use the php version on the cli too) it interprets the html. If you want to see the plain html code in the browser (for whatever reason) wrap a " htmlspecialchars " function call around the $line variable. – edorian Aug 25 '11 at 09:03