且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在<![CDATA [values]]>中获取值使用PHP的DOM?

更新时间: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.

以下是重要的课程:

  • DOMNode —在XML/HTML文档中可以遍历的所有内容的基类,包括文本节点,注释节点和 CDATA节点
  • DOMElement 标签的基类.
  • DOMDocument —文档的基类.包含加载/保存XML的方法以及普通的DOM文档方法(请参见下文).
  • DOMNode — The base class for anything that can be traversed inside an XML/HTML document, including text nodes, comment nodes, and CDATA nodes
  • DOMElement — The base class for tags.
  • DOMDocument — The base class for documents. Contains the methods to load/save XML, as well as normal DOM document methods (see below).

有一些主要的方法和属性:

There are a few staple methods and properties:

  • 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]]>

将所有内容整合在一起:

  1. 创建一个新的文档对象并加载XML
  2. 按标记名称获取所有Destination元素并遍历列表
  3. 遍历每个Destination元素的所有子节点
  4. 检查节点类型是否为XML_CDATA_SECTION_NODE
  5. 如果是,请echo该节点的textContent.
  1. Create a new document object and load the XML
  2. Get all Destination elements by tag name and iterate over the list
  3. Iterate over all child nodes of each Destination element
  4. Check if the node type is XML_CDATA_SECTION_NODE
  5. If it is, 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