1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
<?php $payload = array(array( 'id' => 'email', 'value' => 'test@test.com'), array( 'id' => 'lastName', 'value' => 'test'), array( 'id' => 'firstName', 'value' => 'test'), array( 'id' => 'passwd', 'value' => 'password'), array( 'id' => 'phone', 'value' => 'test'), array( 'id' => 'company', 'value' => 'test'), array( 'id' => 'companySize', 'value' => 'test'), array( 'id' => 'teamSize', 'value' => 'test'), array( 'id' => 'country', 'value' => 'USA'), array( 'id' => 'p', 'value' => 'test')); //Now creating the XML Payload public function create_payload($payload) { if($this->xml) { $xml_packet=' <qdbapi>'; foreach ($fields as $field) { $xml_packet .= '<' . $field['id'] . '>' . $field['value'] . '</' . $field['id'] .'>'; } $xml_packet .= '<ticket>'.$this->ticket.'</ticket> </qdbapi>'; //....more stuff here } }
Refactorings
No refactoring yet !
Marco Valtas
August 12, 2008, August 12, 2008 19:02, permalink
My experience tells that I should avoid create or parse XML files "manually" every time I can. XMLs files can get very complicated and parsing/creating XMLs can be a nightmare.
Well, in PHP I use for cases like this the SimpleXML library (http://www.php.net/manual/en/book.simplexml.php) which usually is already compiled with your PHP dist. For one example similar to your code look at http://www.php.net/manual/en/function.simplexml-element-addChild.php
As for the array above, you could use a simple foreach($array as $key => $value), the example is bellow.
refact
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php $payload = array( 'email' => 'test@test.com', 'lastName' => 'test', 'firstName' => 'test', 'passwd' => 'password', 'phone' => 'test', 'company' => 'test', 'companySize' => 'test', 'teamSize' => 'test', 'country' => 'USA', 'p' => 'test'); foreach($payload as $key => $value) { echo "$key => $value\n"; } ?>
Juha Hollanti
August 12, 2008, August 12, 2008 19:26, permalink
Yeah you're right, parsing XML "manually" isn't usually a very bright idea. But i don't see a problem with creating XML "manually" as long as it's quite simple and straightforward, though.
1 2 3 4 5
echo '<qdapi>';
foreach($payload as $key => $value) {
echo "<$key>$value</$key>";
}
echo '</qdapi>';
Hi. I'm constructing an XML payload with an array. I wonder if there is a more efficient way to form my array than the way I'm currently doing it.