将 Java 代码转换为 PHP - URL 连接和读取响应
我编写了以下 Java 程序来连接 google.com,返回其 HTML 源代码,在屏幕上打印整个源代码,然后计算数量。代码中的换行符 (
)。它运行良好。
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);
}
}
问题是,我想用 PHP 编写类似的代码。 我知道可以使用 fopen 调用 URL,并使用 fread 读入 String 类型变量。
我想知道如何打印它(也许是 echo?)。但更重要的是,我如何在源代码中搜索所需的字符串,而不仅仅是数数。的出现次数,而且还检索指定搜索字符串位置之后的字符串/字符集。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个有点奇怪的请求,您似乎在打印每个单独的数字后打印数字(而不是在最后)。另外,您似乎只对包含
br
的每一行进行一次计数,但这应该可以帮助您开始使用 php: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: