开发者

Easier management of DOM creation of elements in PHP

I'm trying to find an easier way to create <td> elements and inserting text values into them.

There has to be an easier way than creating a new variable for each <td> element, right? Perhaps making a class with some abstraction? Or maybe I'm doing it the wrong way?

At this rate creating 7 <td>s will require me to create 7 variables, 7 different createTextNodes for each of them and 14 more lines of appendChild().

That will be 28 lines for only 7 <td>s. Th开发者_如何学Cis seems excessive to me. Not to mention there's more than one <tr>in the table. Is there any way to shorten the amount of lines I can type to create something like:

<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>

Short example code of what I'm doing:

$doc = new DOMDocument;

$table = $doc->createElement('table');

        $doc->appendChild($table);

        $tr1 = $doc->createElement('tr');
        $table->appendChild($tr1);

        $td1 = $doc->createElement('td');
        $tr1->appendChild($td1);

        $td1_1 = $doc->createElement('td');
        $tr1->appendChild($td1_1);

        $td1_2 = $doc->createElement('td');
        $tr1->appendChild($td1_2);

        $title1 = $doc->createTextNode('This is title #1');
        $title2 = $doc->createTextNode('This is title #2');
        $title3 = $doc->createTextNode('This is title #3');

        $td1->appendChild($title1);
        $td1_1->appendChild($title2);
        $td1_2->appendChild($title3);

        echo $doc->saveXML();

?>


You can add the text to the elements directly:

$doc->createElement('td', 'This is title #1');

Apart from that, there isnt much to shorten in terms of method calls. DOM is a verbose API.


Loops are your friends

$added=array();
for($i=0;$i<7;$i++) {
   $added[]= $doc->createElement('td');
   $tr1->appendChild($td1);

}


Do you know about SimpleXML? Especially: simplexml_load_string() which you can just pass a fragment of XML, and it'll convert it into an object:

$xml=simplexml_load_string("<an><element>This is text</element></an>");
echo $xml->element; // => This is text

Doesn't get easier than that. Unless you just concatenate strings and create a DOM Document from the resulting pseudo-XML to test if it's well-formed by checking the return value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜