Parsing XML with XSLT in WordPress

I am currently trying to load external XML files and parsing them into HTML by using XSL stylesheet file. I’m using the plugin XData Toolkit to achieve this and it is working fine. However, that plugin requires me to create a new query for each XML file and using the shortcode to load the content. As I have a lot of XML files, this method may not be very suitable for me.

Is there a way for me to load a the XML content and parsing it with XSLT dynamically in a page by passing a parameter (ie. the XML file name)?

Read More

Could I do it with PHP script XSLTProcessor? Could I call a PHP script from a page in WordPress? If yes, where do I save the PHP script? Maybe something like this?

<?php

    // Load the XML source
    $xml = new DOMDocument;
    $xml->load('file.xml');

    $xsl = new DOMDocument;
    $xsl->load('stylesheet.xsl');

    // Configure the transformer
    $proc = new XSLTProcessor;
    $proc->importStyleSheet($xsl); // attach the xsl rules

    echo $proc->transformToXML($xml);

?>

I’m not very familiar with WordPress and PHP so any suggestions are welcomed.
Additional information: Using Pagelines Theme and WordPress 3.4.1

Related posts

Leave a Reply

2 comments

  1. For using a parameter(get) in a php script use this:

    $xmlFile = $_GET[‘xml-file’];

    And then just change your code to something like this:

    <?php
    
    $xmlFile = $_GET['xml-file'];
    $xmlDir  ='dirWithXmlFiles/';
    $xmlUri  = $xmlDir . $xmlFile;
    
    if(! file_exists($xmlUri)){
       echo 'some error';
       return;
    }
    
    // Load the XML source
    $xml = new DOMDocument;
    $xml->load($xmlUri);
    
    $xsl = new DOMDocument;
    $xsl->load('stylesheet.xsl');
    
    // Configure the transformer
    $proc = new XSLTProcessor;
    $proc->importStyleSheet($xsl); // attach the xsl rules
    
    echo $proc->transformToXML($xml);
    

    And if you need to add some dynamic content, you can do that by either passing parameters like this:

    $proc->setParam('someNameOfParameter', $someValueOfParameter); 
    

    and use that in the xslt, or build a xml file with content of $xmlUri and the dynamic content as xml.