PHP解析HTML标签 [英] PHP parse HTML tags

查看:98
本文介绍了PHP解析HTML标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:


我对PHP很新颖。
我有一个字符串变量中某个页面的body标签的文本。
我想知道它是否包含一些标签...其中给出了标签名称tag1,如果是,则只从该字符串中获取该标签。
我怎么能在PHP中简单地做到这一点?



感谢!!

解决方案您可能会看到类似这样的内容:

 <?php 
$ content = ;
$ doc = new DOMDocument();
$ doc-> load(example.html);
$ items = $ doc-> getElementsByTagName('tag1');
if(count($ items)> 0)//只有找到tag1项目
{
foreach($ items as $ tag1)
{
/ /使用$ tag1-> nodeValue做些事情并保存您的修改
$ content。= $ tag1-> nodeValue;
}
}
else
{
$ content = $ doc-> saveHTML();
}
echo $ content;
?>

DomDocument 代表整个HTML或XML文档;充当文档树的根。因此,您将拥有有效的标记,并且通过标记名称查找元素,您将无法找到注释。


Possible Duplicate:
How to parse and process HTML with PHP?

I'm pretty new to PHP. I have the text of a body tag of some page in a string variable. I'd like to know if it contains some tag ... where the tag name tag1 is given, and if so, take only that tag from the string. How can I do that simply in PHP?

Thanks!!

解决方案

You would be looking at something like this:

<?php
$content = "";
$doc = new DOMDocument();
$doc->load("example.html");
$items = $doc->getElementsByTagName('tag1');
if(count($items) > 0) //Only if tag1 items are found 
{
    foreach ($items as $tag1)
    {
         // Do something with $tag1->nodeValue and save your modifications
         $content .= $tag1->nodeValue;
    }
}
else
{
     $content = $doc->saveHTML();
}
echo $content;
?>

DomDocument represents an entire HTML or XML document; serves as the root of the document tree. So you will have a valid markup, and by finding elements By Tag Name you won't find comments.

这篇关于PHP解析HTML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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