php:从html解析字符串 [英] php: Parse string from html

查看:91
本文介绍了php:从html解析字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用

file_get_contents('http://www.example.com/file.html')

,并想解析包含ParseThis的行:

and want to parse the line including "ParseThis":

 <h1 class=\"header\">ParseThis<\/h1>

正如你所看到的,它在一个 h1 标签(文件中的第一个 h1 标记)。如何获取文本ParseThis?

As you can see, it's within an h1 tag (the first h1 tag from the file). How can I get the text "ParseThis"?

推荐答案

您可以使用 DOM

// Load remote file, supress parse errors
libxml_use_internal_errors(TRUE);
$dom = new DOMDocument;
$dom->loadHTMLFile('http://www.example.com/file.html');
libxml_clear_errors();

// use XPath to find all nodes with a class attribute of header
$xp = new DOMXpath($dom);
$nodes = $xp->query('//h1[@class="header"]');

// output first item's content
echo $nodes->item(0)->nodeValue;

另见

  • Best methods to parse HTML
  • More examples by me with DOM.

标记这个CW,因为我以前回答过,但我太懒了,找不到重复的

这篇关于php:从html解析字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆