In order to refer to a local DTD when using PHP SimpleXML, I need to convert the absolute path into a file type URI. For example, convert /home/sitename/www/xml/example.dtd to file:///home/sitename/www/xml/example.dtd.
In the example given, it is easy enough, since all that is required is to add the 'file' scheme in front of the path. But if a situation arises such as there being a blank in one of the directory names, this is not good enough. The mechanism should work on Windows or Linux, and allow for non-ASCII characters in the directory names.
The code devised so far is:
$absparts = explode('/', _ALIRO_ABSOLUTE_PATH);
$driveletter = (0 == strncasecmp(PHP_OS, 'win', 3)) ? array_shift($absparts) : '';
$filename = $driveletter.implode('/', array_map('rawurlencode', $absparts)).'/xml/'.$filename.'.dtd';
$href = 'file:///'.$filename;
where the defined symbol is the absolute path to the system root (always with forwards slashes), the DTD is in the xml subdirectory, and has a name of $filename followed by the extension .dtd.
Will this work correctly? Is there a better approach?
Let me explain a little more background. The aim is to parse an XML document using SimpleXML. This is done using the simplexml_load_string() function with the LIBXML_DTDVALID option. The XML document will contain a real URI pointing to a home web site, but I do not want to introduce delays involved in reaching a distant web site, or load up the home web site with requests. The reference to the DTD is therefore edited so as to refer to the local machine. But it has to be embedded as a URI within a DOCTYPE inside the XML document. The constraints are not my choice, they are implicit in the rules for a DOCTYPE and are enforced by the SimpleXML function. I can work out where the file is located as an absolute path, but to put it into a DOCTYPE, it must be converted into a URI.