更新时间:2023-02-23 11:07:55
使用PHP DOM非常简单,并且与Javascript DOM非常相似.
Working with PHP DOM is fairly straightforward, and is very similar to Javascript's DOM.
以下是重要的课程:
有一些主要的方法和属性:
There are a few staple methods and properties:
DOMDocument->load()
—创建新的DOMDocument
后,请对该对象使用此方法从文件中加载.DOMDocument->getElementsByTagName()
—此方法返回具有给定标签名称的文档中所有元素的节点列表.然后,您可以在此列表上进行迭代(foreach
).DOMNode->childNodes
—节点的所有子节点的节点列表. (请记住, CDATA 部分是一个节点!)DOMNode->nodeType
—获取节点的类型. CDATA节点的类型为 XML_CDATA_SECTION_NODE ,这是一个值为 4 的常量.DOMNode->textContent
—获取任何节点的文本内容.DOMDocument->load()
— After creating a new DOMDocument
, use this method on that object to load from a file.DOMDocument->getElementsByTagName()
— this method returns a node list of all elements in the document with the given tag name. Then you can iterate (foreach
) on this list.DOMNode->childNodes
— A node list of all children of a node. (Remember, a CDATA section is a node!)DOMNode->nodeType
— Get the type of a node. CDATA nodes have type XML_CDATA_SECTION_NODE, which is a constant with the value 4.DOMNode->textContent
— get the text content of any node. 注意:您的CDATA部分格式不正确.我不知道为什么在第一个中有一个额外的]]
,或者在行的末尾有一个未封闭的CDATA部分,但我认为应该只是:
Note: Your CDATA sections are malformed. I don't know why there is an extra ]]
in the first one, or an unclosed CDATA section at the end of the line, but I think it should simply be:
<![CDATA[Aghia Paraskevi, Skiatos, Greece]]>
将所有内容整合在一起:
Destination
元素并遍历列表Destination
元素的所有子节点XML_CDATA_SECTION_NODE
echo
该节点的textContent
.Destination
elements by tag name and iterate over the listDestination
elementXML_CDATA_SECTION_NODE
echo
the textContent
of that node.代码:
$doc = new DOMDocument();
$doc->load('test.xml');
$destinations = $doc->getElementsByTagName("Destination");
foreach ($destinations as $destination) {
foreach($destination->childNodes as $child) {
if ($child->nodeType == XML_CDATA_SECTION_NODE) {
echo $child->textContent . "<br/>";
}
}
}
结果:
希腊斯基亚托斯的Aghia Paraskevi
西班牙Amettla
希腊Amoliani
德国博布林根
Aghia Paraskevi, Skiatos, Greece
Amettla, Spain
Amoliani, Greece
Boblingen, Germany