如何在PHP的DOMDocument中获取特定的标记?

时间:2022-10-27 10:22:35

I have variable documents that I need to modify on the fly. For example, I could have a document as follows:

我有需要修改的可变文档。例如,我可以有如下文件:

<!--?xml version="1.0"?-->
<item>
    <tag1></tag1>
</item>
<tag2>
    <item></item>
    <item></item>
</tag2>

This is very simplified, but I have tags with the same name at different levels. I want to get the item tags within 'tag2'. The actual tags in the files I am given have unique IDs to differentiate them as well as some other attributes. I need to find the tag, comment it out, and save the xml. I was able to get DOMDocument to return the 'tag2' node, but I'm not sure how to access the item tags within that structure.

这是非常简化的,但是我有不同级别上相同名称的标记。我想要在'tag2'中获得项目标签。给我的文件中的实际标记有惟一的id来区分它们以及其他一些属性。我需要找到标记,注释掉它,然后保存xml。我能够让DOMDocument返回'tag2'节点,但我不确定如何访问该结构中的项标记。

3 个解决方案

#1


4  

This is the kind of problem that PHP's DOMDocument class excels at. First load the XML string using loadHTML() method, and then use an XPath expression to traverse the DOM tree:

这是PHP的DOMDocument类所擅长的问题。首先使用loadHTML()方法加载XML字符串,然后使用XPath表达式遍历DOM树:

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$item_tags = $xpath->query('//tag2/item');
foreach ($item_tags as $tag) {
    echo $tag->tagName, PHP_EOL; // example
}

Online demo

在线演示

#2


1  

<?php
$tag= new DOMDocument();
$tag->loadHTML($string);

foreach ($tag->getElementsByTagName("tag") as $element) 
{
    echo $tag->saveXML($element);
}
?>

may be helps you .try it

可能对你有帮助。试试吧

#3


0  

$DOMNode -> attributes -> getNamedItem( 'yourAttribute' ) -> value;

#1


4  

This is the kind of problem that PHP's DOMDocument class excels at. First load the XML string using loadHTML() method, and then use an XPath expression to traverse the DOM tree:

这是PHP的DOMDocument类所擅长的问题。首先使用loadHTML()方法加载XML字符串,然后使用XPath表达式遍历DOM树:

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$item_tags = $xpath->query('//tag2/item');
foreach ($item_tags as $tag) {
    echo $tag->tagName, PHP_EOL; // example
}

Online demo

在线演示

#2


1  

<?php
$tag= new DOMDocument();
$tag->loadHTML($string);

foreach ($tag->getElementsByTagName("tag") as $element) 
{
    echo $tag->saveXML($element);
}
?>

may be helps you .try it

可能对你有帮助。试试吧

#3


0  

$DOMNode -> attributes -> getNamedItem( 'yourAttribute' ) -> value;