PHP DOM XML ayrıştırma basitleştirmek - nasıl?

0 Cevap php

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.

Örnek XML fragmanı:

-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
            ...

Benim orijinal fikir ben eski CSV'leri dışarı atmak ve XMLs kullanmaya başladı böylece müvekkilimin iş akışını hızlandırmak oldu.

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).

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

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 />";
    }
}

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.

Eğer bana yardım edin.

Thanks, fabrik

0 Cevap