OK upfront, I’m a newb on PHP and Java, however trying to refresh my coding after journeying into management for the past ten years.
I have a table in the form:
heading1_sub1_element1 = data1
heading1_sub1_element2 = data2
heading1_sub1_element3 = data3
heading1_sub2_element1 = data4
heading1_sub2_element2 = data5
heading1_sub2_element3 = data6
Using the awesome example at Tony Marsden’s site I have been able to get the table to extract the data into the form:
<table>
<heading1_sub1_element1>data1</heading1_sub1_element1>
<heading1_sub1_element2>data2</heading1_sub1_element2>
<heading1_sub1_element3>data3</heading1_sub1_element3>
<heading1_sub2_element1>data4</heading1_sub2_element1>
<heading1_sub2_element2>data5</heading1_sub2_element2>
<heading1_sub2_element3>data6</heading1_sub2_element3>
</table>
However what I would like to get to is:
<heading1>
<sub1>
<element1>Data1</element1>
<element2>Data2</element2>
<element3>Data3</element3>
</sub1>
<sub2>
<element1>Data4</element1>
<element2>Data5</element2>
<element3>Data6</element3>
</sub2>
</heading1>
Does anyone have any idea on how to get the data into that format? will I need to use XSLT, or can PHP do this directly?
My only reason for doing this is that the XML looks a whole load better.
Thanks in advance, and any assistance will be greatfully recieved.
Here is a generic solution that correctly processes any set of lines having the specified format — even if there are different number of underscores on each line and the first “name” isn’t the same on all lines:
when this transformation is applied on the following XML document (the given lines, wrapped into a top element to make this a well-formed XML document):
the wanted, correct result is produced:
When applying the same transformation to this, much more complicated XML document:
we again get the correct, wanted result:
Explanation:
This is a two-pass processing:
…..
.2. In the second pass we perform a specific kind of grouping so that we produce the wanted result.
Note: In this solution we access the input strings as the only text node child of the only element in an XML document. This infact isn’t necessary and I have done so only for convenience. We can read the strings from an external text file using the standard XSLT 2.0 function
unparsed-text().