2

Reading a XML processing instruction with PHP

Posted in php at October 21st, 2008 /

I’m doing some XSL transformations in a project I’m involved in right now. The XML documents that are beeing transformed all include a xml-stylesheet processing instruction that I need to read in order to know what stylesheet to use for a specfic document. To my surprise, reading processing instructions from a DOMDocument in PHP was not so easy as one might assume.

I wont go into details and tell you about all the hair (of which I have very little) I lost during my search for a way to get ahold of those processing instructions. In the end I used a XPath expression to select the PI. Below you’ll find the code I used.

$doc = new DOMDocument;
$doc->load("document.xml");
$xpath = new DOMXpath($doc);
$nodes = $xpath->evaluate("/child::processing-instruction('xml-stylesheet')");
if(!empty($nodes))
$pi = $nodes->item(0);
print $pi->target;
print $pi->data;

Published in php

2 Responses to “Reading a XML processing instruction with PHP”

  1. January 9th, 2009 at 7:52 pm #Chris

    Thank you, this was very helpful. I was going to fallback on the XML Parser class for this functionality, but this is much nicer.

  2. January 16th, 2009 at 5:19 am #Jakob

    Thanks. I hadn’t been able to find any information on this anywhere else, so I’ve been using a regular expression so far, but this looks more right :)

Leave a Reply