Note that there are some explanatory texts on larger screens.

plurals
  1. POSimplify PHP DOM XML parsing - how?
    primarykey
    data
    text
    <p>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.</p> <p>Sample XML fragment:</p> <pre><code>-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 ... </code></pre> <p>My original idea was to speed up my client's workflow so i throw out old CSVs and started using XMLs.</p> <p><strong>Problem 1:</strong> When i grouping products into page i'm using <a href="http://www.php.net/manual/en/domelement.setidattribute.php" rel="noreferrer">setIdAttribute</a> 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 <a href="http://www.php.net/manual/en/domdocument.getelementbyid.php" rel="noreferrer">getElementById</a>).</p> <p><em>Question 1:</em> How can i write a simple DTD which provides these necessary informations so i can use <code>getElementById</code> at the reading phase too?</p> <p><strong>Problem 2:</strong> 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 (<code>getElementById</code> 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:</p> <pre><code>$doc = DOMDocument::load('data.xml'); $xpath = new DOMXPath($doc); $query = '/pages/page[' . $page . ']'; //$page is fine: was set earlier $products = $xpath-&gt;query($query); $_prods = $doc-&gt;getElementsByTagName('product'); foreach($_prods as $product){ foreach($product-&gt;childNodes as $node){ echo $node-&gt;nodeName . ": " . $node-&gt;nodeValue . "&lt;br /&gt;"; } } </code></pre> <p><em>Queston 2:</em> I think the code above is the example about <em>how not</em> 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.</p> <p>Please help me if you can.</p> <p>Thanks, fabrik</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload