7
votes

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

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

2

2 Answers

0
votes

Wordpress has a built-in XML processor that may be simpler to use if you're end-goal is to display the content.

If it's easier to include a PHP script that you wrote to convert the feeds or import a library, you can put the script in the theme's folder (i.e. /wp-content/themes/pagelines/) and call it with include_once:

include_once(get_template_directory().'/FILENAME.php');

0
votes

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.