Hi All,
I have the following XML string…
[CODE]<?xml version=”1.0″ encoding=”UTF-8″?>
<data>
<username>bWlkYXNwcmludC5jb20=</username>
<password>NUM3NEQwRTI=</password>
<products><product>
<type>Poster</type>
<height units=”millimeters”>297</height>
<width units=”millimeters”>210</width>
</product><product>
<type>Poster</type>
<height units=”millimeters”>420</height>
<width units=”millimeters”>297</width>
</product><product>
<type>Poster</type>
<height units=”millimeters”>594</height>
<width units=”millimeters”>420</width>
</product><product>
<type>Poster</type>
<height units=”millimeters”>841</height>
<width units=”millimeters”>594</width>
</product><product>
<type>Poster</type>
<height units=”millimeters”>1189</height>
<width units=”millimeters”>841</width>
</product></products>
<test></test>
</data>
…and this modified function I’m using to parse it into a well formed structure…
[code=php]function formatXML($xml)
{
// parse into continuous str
$xml = str_replace(“n”, ”, $xml);
$xml = str_replace(‘ ‘, ”, $xml);
$xml = str_replace(“t”, ”, $xml);
$xml = str_replace(‘> ‘, ”, $xml);
$xml = str_replace(‘ <‘, ”, $xml);
// http://recurser.com/articles/2007/04/05/format-xml-with-php/
$xml = preg_replace(‘/(>)(<)(/*)/’, “$1n$2$3”, $xml);
$token = strtok($xml, “n”);
$result = ”;
$pad = 0;
$matches = array();
while ($token !== false)
{
if (preg_match(‘/.+</w[^>]*>$/’, $token, $matches)) {
$indent = 0;
} elseif (preg_match(‘/^</w/’, $token, $matches)) {
$pad–;
} elseif (preg_match(‘/^<w[^>]*[^/]>.*$/’, $token, $matches)) {
$indent=1;
} else {
$indent = 0;
}
$line = str_repeat(“t”, $pad) . $token;
$result .= $line . “n”;
$token = strtok(“n”);
$pad += $indent;
}
return $result;
}
…which results in this…
[CODE]<?xml version=”1.0″ encoding=”UTF-8″?>
<data>
<username>bWlkYXNwcmludC5jb20=</username>
<password>NUM3NEQwRTI=</password>
<products>
<product>
<type>Poster</type>
<height units=”millimeters”>297</height>
<width units=”millimeters”>210</width>
</product>
<product>
<type>Poster</type>
<height units=”millimeters”>420</height>
<width units=”millimeters”>297</width>
</product>
<product>
<type>Poster</type>
<height units=”millimeters”>594</height>
<width units=”millimeters”>420</width>
</product>
<product>
<type>Poster</type>
<height units=”millimeters”>841</height>
<width units=”millimeters”>594</width>
</product>
<product>
<type>Poster</type>
<height units=”millimeters”>1189</height>
<width units=”millimeters”>841</width>
</product>
</products>
[COLOR=”Red”]<test>
</test>
</data>[/COLOR]
My problem is with the empty <test></test> tag. When it is processed by my function a newline character is placed in it and the next tag (the closing </data> tag gets tabbed over).
I can’t work out a fix for the life of me!
Can anyone help?
Thanks!
dai.hop