Basically, I'm taking an SQL query and converting it into a dynamic XML. I'm trying to create custom XML tags for elements that I obtain from my query, and I'd like to pick and choose which results from my query are used as XML elements.
In a perfect world, I'd like to be able to take each row that I get from the query and determine the XML properties. I'd like for this to be a loop, but I just can't seem to get it to work.
$sql = "SELECT
COUNT( l.log_id ) AS id,
l.status AS 'requestStatus',
d.firmname AS 'name',
DAY (FROM_UNIXTIME( l.time ) ) AS DAY,
WEEK( FROM_UNIXTIME( l.time ) ) AS week,
YEAR( FROM_UNIXTIME( l.time ) ) AS year
FROM $table_id1, $table_id2
WHERE
l.client = 'XXXXX' AND
l.time > 1 AND
l.work_id = d.subid AND
d.deleted = 0 AND
d.user_id = l.user_id
GROUP BY
YEAR( FROM_UNIXTIME( l.time ) ),
WEEK( FROM_UNIXTIME( l.time ) )
ORDER BY
week DESC";
$dbresult = mysql_query($sql);
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
$doc->formatOutput = true;
// create root node
$root = $doc->createElement('workResponse');
$root = $doc->appendChild($root);
$occ2 = $doc->createElement('contentResponses');
$occ2 = $root->appendChild($occ2);
// process one row at a time
while($row = mysql_fetch_assoc($dbresult)) {
// add node for each row
$occ = $doc->createElement("contentResponse");
$occ = $root->appendChild($occ);
// add a child node for each field
foreach ($row as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
} // foreach
}// while
// get completed xml document
$xml_string = $doc->saveXML();
echo $xml_string;
?>
First, I suggest not using mysql_*
functions. They are deprecated and going away .
Dom extension seems to be overkill in this situation. I prefer to use SimpleXML when I can.
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test','username','password');
$sxe = new SimpleXMLElement('<workResponse></workResponse>');
$sxe_crs = $sxe->addChild('contentResponses');
function array_walk_simplexml(&$value, $key, &$sx) {
$sx->addChild($key, $value);
}
$stmt = $dbh->query('SELECT * FROM sometable');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$sx_cr = $sxe_crs->addChild('contentResponse');
array_walk($row, 'array_walk_simplexml', $sx_cr);
}
echo $sxe->asXML();
If you want to "pretty print" the XML (admire your work?), then you'll need to use the Dom extension.
$dom_sxe = dom_import_simplexml($sxe);
$dom = new DOMDocument('1.0');
$dom->formatOutput = true;
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);
echo $dom->saveXML();
XML_Serializer对php pear用户非常有用
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.