Please help - xml & xslt

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
getmizanur
Forum Commoner
Posts: 71
Joined: Sun Sep 06, 2009 12:28 pm

Please help - xml & xslt

Post by getmizanur »

elloo,

I'm new to XML and XSLT and I've thought to learn more about it by trying do something basic. In this exercise I try to query the company.xml file using xpath and trying to save the result in result.xml.

When I run my code I get this in result.xml:

Code: Select all

 
<?xml version="1.0" encoding="UTF-8"?>
<annual>
    <company>
        <turnover id="2001">100,000</turnover>
        <turnover id="2002">200,000</turnover>
        <turnover id="2003">300,000</turnover>
        <employee id="001">Dicovery</employee>
    </company>
    <company>
        <turnover id="2001">300,000</turnover>
        <turnover id="2002">300,000</turnover>
        <turnover id="2003">400,000</turnover>
        <employee id="002">World</employee>
    </company>
</annual>
 
However my output should be this in result.xml

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<annual>
    <company>
        <turnover id="2001">100,000</turnover>
        <turnover id="2002">200,000</turnover>
        <turnover id="2003">300,000</turnover>
        <employee id="001">Dicovery</employee>
    </company>
</annual>
 ##################Here is my Code#################company.xml

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<annual>
    <company>
        <turnover id="2001">100,000</turnover>
        <turnover id="2002">200,000</turnover>
        <turnover id="2003">300,000</turnover>
        <employee id="001">Dicovery</employee>
    </company>
    <company>
        <turnover id="2001">300,000</turnover>
        <turnover id="2002">300,000</turnover>
        <turnover id="2003">400,000</turnover>
        <employee id="002">World</employee>
    </company>
</annual>
 test.php

Code: Select all

<?php
function xmlQuery($xpath) {
    $mXmlDoc = new DOMDocument();
    if(!($mXmlDoc->load('company.xml'))) {
        trigger_error();
    }
    $mXpath = new DOMXPath($mXmlDoc);       
    $node_list = $mXpath->query($xpath, $mXmlDoc);
 
    foreach($node_list as $node) {
        echo $mXmlDoc->saveXML($node);
    }
    
    $mXmlDoc->save('try.xml');
}
 
xmlQuery("/annual/company[employee[@id = '001']]");
?>
 
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Re: Please help - xml & xslt

Post by Ollie Saunders »

Try outputting directly, not to a file. I can't see anything wrong with your code (that's not to say it's correct though, the last time I used the PHP XPath API was quite a while ago).
Post Reply