简化 PHP DOM XML 解析 - 如何? [英] Simplify PHP DOM XML parsing - how?

查看:34
本文介绍了简化 PHP DOM XML 解析 - 如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经花了一整天的时间使用 PHP 的 DOM 函数,但我还不明白它是如何工作的.:(我有一个简单的 XML 文件,看起来不错,但我无法像创建它的结构时那样使用它.

I've spent whole days with PHP's DOM functions but i can't understand how it works yet. :( I have a simple XML file that looks okay but i cannot use it how i think when i've created it's structure.

示例 XML 片段:

-pages //root element
    -page id="1" //we can have any number of pages
        -product id="364826" //we can have any number of products
            -SOME_KIND_OF_VALUE
            -ANOTHER_VALUE
            ...

我最初的想法是加快我客户的工作流程,所以我扔掉了旧的 CSV 并开始使用 XML.

My original idea was to speed up my client's workflow so i throw out old CSVs and started using XMLs.

问题 1:当我将产品分组到页面中时,我使用 setIdAttribute 来防止存储树中的同一页不止一次.这工作正常,直到读取发生,因为这些 id 与某种 DTD 相关联(基于 getElementById).

Problem 1: When i grouping products into page i'm using setIdAttribute to prevent storing the same page in the tree more than once. This works fine until reading happens because these id's are tied to some kind of DTD's (based on getElementById).

问题 1:我如何编写一个简单的 DTD 来提供这些必要的信息,以便我也可以在阅读阶段使用 getElementById?

Question 1: How can i write a simple DTD which provides these necessary informations so i can use getElementById at the reading phase too?

问题 2:因为我有页面,所以我想加载尽可能少的信息.这就是我在页面上创建 id 属性的原因.现在我无法直接访问我的页面 id="2" 因为上面的问题 1(getElementById 目前没有意义).不知何故,我可以设法检索给定页面上每个产品的必要信息,但我的代码看起来很可怕:

Problem 2: Because i have pages i'd like to load as less information as i can. That was why i created the id attribute on pages. Now i cannot access my page id="2" directly because Problem 1 above (getElementById makes no sense currently). Somehow i can managed to retrieve the necessary informations about each product on a given page but my code looks scary:

$doc      = DOMDocument::load('data.xml');
$xpath    = new DOMXPath($doc);
$query    = '/pages/page[' . $page . ']'; //$page is fine: was set earlier
$products = $xpath->query($query);
$_prods   = $doc->getElementsByTagName('product');
foreach($_prods as $product){
    foreach($product->childNodes as $node){
        echo $node->nodeName . ": " . $node->nodeValue . "<br />";
    }
}

问题 2:我认为上面的代码是关于如何不解析 XML 的示例.但是由于我对 PHP 的 DOM 函数的了解有限,我无法自己编写一个更清晰的函数.我尝试了一些微不足道的解决方案,但没有一个对我有用.

Queston 2: I think the code above is the example about how not to parse an XML. But because of my limited knowledge of PHP's DOM functions i cannot write a cleaner one by myself. I tried some trivial solution but none of them worked for me.

推荐答案

解决问题1:

W3C 定义:属性 xml:id 作为 XML 文档中的 ID 属性的含义,并定义了此属性的处理以在没有验证的情况下识别 ID,而不获取外部资源,以及不依赖于内部子集.

The W3C defines: the meaning of the attribute xml:id as an ID attribute in XML documents and defines processing of this attribute to identify IDs in the absence of validation, without fetching external resources, and without relying on an internal subset.

换句话说,当你使用

$element->setAttribute('xml:id', 'test');

您不需要调用 setIdAttribute,也不需要指定 DTD 或 Schema.当与 getElementById 一起使用时,DOM 将识别 xml:id 属性,而无需验证文档或任何内容.这是最省力的方法.但请注意,根据您的操作系统和 libxml 版本,您根本无法使用 getElementById.

you do not need to call setIdAttribute, nor specify a DTD or Schema. DOM will recognize the xml:id attribute when used with getElementById without you having to validate the document or anything. This is the least effort approach. Note though, that depending on your OS and version of libxml, you wont get getElementById to work at all.

解决问题 2:

即使使用 getElementById 无法获取 ID,您仍然可以使用 XPath 获取它们:

Even with IDs not being fetchable with getElementById, you can still very much fetch them with XPath:

$xpath->query('/pages/page[@id=1]');

肯定有用.您还可以直接获取特定页面的产品子项:

would definitely work. And you can also fetch the product children for a specific page directly:

$xpath->query('//pages/page[@id=1]/products');

除此之外,您几乎无法使 DOM 代码看起来不那么冗长,因为它确实是一个冗长的界面.必须如此,因为 DOM 是一种语言不可知的界面,再次由 W3C 定义.

Apart from this, there is very little you can do to make DOM code look less verbose, because it really is a verbose interface. It has to be, because DOM is a language agnostic interface, again defined by the W3C.

在下方评论后编辑

它像我上面解释的那样工作.这是一个完整的测试用例.第一部分用于编写 带有 DOM 的新 XML 文件.这就是您需要设置 xml:id 属性的地方.您可以使用它而不是常规的、非命名空间的 id 属性.

It is working like I explained above. Here is a full test case for you. The first part is for writing new XML files with DOM. That is where you need to set the xml:id attribute. You use this instead of the regular, non-namespaced, id attribute.

// Setup
$dom = new DOMDocument;
$dom->formatOutput = TRUE;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML('<pages/>');

// How to set a valid id attribute when not using a DTD or Schema
$page1 = $dom->createElement('page');
$page1->setAttribute('xml:id', 'p1');
$page1->appendChild($dom->createElement('product', 'foo1'));
$page1->appendChild($dom->createElement('product', 'foo2'));

// How to set an ID attribute that requires a DTD or Schema when reloaded
$page2 = $dom->createElement('page');
$page2->setAttribute('id', 'p2');
$page2->setIdAttribute('id', TRUE);
$page2->appendChild($dom->createElement('product', 'bar1'));
$page2->appendChild($dom->createElement('product', 'bar2'));

// Appending pages and saving XML
$dom->documentElement->appendChild($page1);
$dom->documentElement->appendChild($page2);
$xml = $dom->saveXML();
unset($dom, $page1, $page2);
echo $xml;

这将创建一个像这样的 XML 文件:

This will create an XML file like this:

<?xml version="1.0"?>
<pages>
  <page xml:id="p1">
    <product>foo1</product>
    <product>foo2</product>
  </page>
  <page id="p2">
    <product>bar1</product>
    <product>bar2</product>
  </page>
</pages>

当您再次读取 XML 时,新的 DOM 实例不再知道您已使用 setIdAttribute<将非命名空间的 id 属性声明为 ID 属性/代码>.它仍将在 XML 中,但 id 属性将只是一个常规属性.您必须意识到 ID 属性在 XML 中是特殊的.>

When you read in the XML again, the new DOM instance no longer knows you have declared the non-namespaced id attribute as ID attribute with setIdAttribute. It will still be in the XML, but id attribute will just be a regular attribute. You have to be aware that ID attributes are special in XML.

// Load the XML we created above
$dom = new DOMDocument;
$dom->loadXML($xml);

现在进行一些测试:

echo "

 GETELEMENTBYID RETURNS ELEMENT WITH XML:ID 

";
foreach( $dom->getElementById('p1')->childNodes as $product) {
    echo $product->nodeValue; // Will output foo1 and foo2 with whitespace
}

以上有效,因为符合 DOM 的解析器必须识别 xml:id 是 ID 属性,而不管任何 DTD 或架构.这在上面链接的规范中进行了解释.它输出空白的原因是因为格式化输出在开始标签、两个产品标签和结束标签之间有 DOMText 节点,所以我们迭代了五个节点.在处理 XML 时,节点概念对于理解至关重要.

The above works, because a DOM compliant parser has to recognize xml:id is an ID attribute, regardless of any DTD or Schema. This is explained in the specs linked above. The reason it outputs whitespace is because due to the formatted output there is DOMText nodes between the opening tag, the two product tags and the closing tags, so we are iterating over five nodes. The node concept is crucial to understand when working with XML.

echo "

 GETELEMENTBYID CANNOT FETCH NORMAL ID 

";
foreach( $dom->getElementById('p2')->childNodes as $product) {
    echo $product->nodeValue; // Will output a NOTICE and a WARNING
}

上述方法不起作用,因为 id 不是 ID 属性.为了让 DOM 解析器识别它,您需要一个 DTD 或架构,并且必须针对它验证 XML.

The above will not work, because id is not an ID attribute. For the DOM parser to recognize it as such, you need a DTD or Schema and the XML must be validated against it.

echo "

 XPATH CAN FETCH NORMAL ID 

";
$xPath = new DOMXPath($dom);
$page2 = $xPath->query('/pages/page[@id="p2"]')->item(0);
foreach( $page2->childNodes as $product) {
    echo $product->nodeValue; // Will output bar1 and bar2
}

另一方面,XPath 是关于属性的文字,这意味着如果 getElementById 不可用,您可以查询具有属性 id 的页面元素的 DOM.请注意,要查询 ID 为 p1 的页面,您必须包含命名空间,例如@xml:id="p1".

XPath on the other hand is literal about the attributes, which means you can query the DOM for the page element with attribute id if getElementById is not available. Note that to query the page with ID p1, you'd have to include the namespace, e.g. @xml:id="p1".

echo "

 XPATH CAN FETCH PRODUCTS FOR PAGE WITH ID 

";
$xPath = new DOMXPath($dom);
foreach( $xPath->query('/pages/page[@id="p2"]/product') as $product ) {
    echo $product->nodeValue; // Will output bar1 and bar2 wout whitespace
}

而且如上所述,您还可以使用 XPath 查询文档中的任何其他内容.这个不会输出空格,因为它只会返回id为p2的页面下方的product元素.

And like said, you can also use XPath to query anything else in the document. This one will not output whitespace, because it will only return the product elements below the page with id p2.

你也可以从一个节点遍历整个 DOM.这是一个树状结构.由于 DOMNode 是 DOM 中最重要的类,您想熟悉它.

You can also traverse the entire DOM from a node. It's a tree structure. Since DOMNode is the most important class in DOM, you want to familiarize yourself with it.

echo "

 TRAVERSING UP AND DOWN 

";
$product = $dom->getElementsByTagName('product')->item(2);
echo $product->tagName; // 'product'
echo $dom->saveXML($product); // '<product>bar1</product>'

// Going from bar1 to foo1
$product = $product->parentNode // Page Node
                   ->parentNode // Pages Node
                   ->childNodes->item(1)  // Page p1
                   ->childNodes->item(1); // 1st Product

echo $product->nodeValue; // 'foo1'

// from foo1 to foo2 it is two(!) nodes because the XML is formatted
echo $product->nextSibling->nodeName; // '#text' with whitespace and linebreak
echo $product->nextSibling->nextSibling->nodeName; // 'product'
echo $product->nextSibling->nextSibling->nodeValue; // 'foo2'

顺便说一句,是的,我在上面的原始代码中有一个错字.它是 product 不是 products.但是我发现,当您只需要更改 s 时,声称代码不起作用几乎没有道理.感觉太想被勺子喂了.

On a sidenote, yes, I do have a typo in the original code above. It's product not products. But I find it hardly justified to claim the code does not work when all you have to change is an s. That just feels too much like wanting to be spoonfed.

这篇关于简化 PHP DOM XML 解析 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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