使用 PHP 获取页面的 HTML 源代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5012400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get HTML source code of page with PHP
提问by JJJollyjim
If I have the html file:
如果我有 html 文件:
<!doctype html>
<html>
<head></head>
<body>
<!-- Begin -->
Important Information
<!-- End -->
</body>
</head>
</html>
How can I use PHP to get the string "Important Information" from the file?
如何使用 PHP 从文件中获取字符串“重要信息”?
采纳答案by Endophage
If you already have the parsing sorted, just use file_get_contents()
. You can pass it a URL and it will return the content found at the URL, in this case, the html. Or if you have the file locally, you pass it the file path.
如果您已经对解析进行了排序,只需使用file_get_contents()
. 您可以向它传递一个 URL,它会返回在 URL 中找到的内容,在本例中为 html。或者,如果您在本地拥有该文件,则将文件路径传递给它。
回答by Murilo Vasconcelos
In this simple example you can open the file and do fgets()
until you find a line with <!-- Begin -->
and saving the lines until you find <!-- End -->
.
在这个简单的示例中,您可以打开文件并执行fgets()
直到找到一行<!-- Begin -->
并保存这些行直到找到<!-- End -->
.
If your HTML is in a variable you can just do:
如果您的 HTML 位于变量中,您可以执行以下操作:
<?php
$begin = strpos($var, '<!-- Begin -->') + strlen('<!-- Begin -->'); // Can hardcode this with 14 (the length of your 'needle'
$end = strpos($var, '<!-- End -->');
$text = substr($var, $begin, ($end - $begin));
echo $text;
?>
You can see the output here.
您可以在此处查看输出。
回答by Manish Trivedi
You can fetch "HTML" by this
你可以通过这个获取“HTML”
//file_get_html function from third party library
// Create DOM from URL or file
$html = file_get_html('http://www.example.com/');
and any operation on DOM then read following docs: http://de.php.net/manual/en/book.dom.php
以及对 DOM 的任何操作,然后阅读以下文档:http: //de.php.net/manual/en/book.dom.php