note 105388 modified in function.mysql-field-name by danbrown

From: Date: Sun, 14 Aug 2011 16:42:21 +0000
Subject: note 105388 modified in function.mysql-field-name by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-182479@lists.php.net to get a copy of this message
simple sql to xml converter works with any sql query and returns the name of the table as the root element "row" as each row element and the names of the columns are your children of row. fully tested. <?php function sqlToXml($host,$user,$pass,$database,$tablename,$query){ $link = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error()); $db = mysql_select_db($database, $link) or die(mysql_error()); $result = mysql_query($query); if(!$result){ die('Invalid query: '.mysql_error()); } $numOfCols = mysql_num_fields($result); $numOfRows = mysql_num_rows($result); $info = mysql_fetch_assoc($result); //send headers header('Content-type: text/xml'); header('Pragma: public'); header('Cache-control: private'); header('Expires: -1'); $xml = '<?xml version="1.0" encoding="utf-8"?>'; $xml.= "<{$tablename}>"; if($numOfRows > 0){ do { $xml.= "<row>"; foreach($info as $column => $value) { $xml.= "<{$column}>{$value}</{$column}>"; } $xml.= "</row>"; } while ($info = mysql_fetch_array($result)); } $xml.= "</{$tablename}>"; mysql_free_result($result); return $xml; } ?> --was-- simple sql to xml converter works with any sql query and returns the name of the table as the root element "row" as each row element and the names of the columns are your children of row. fully tested. function sqlToXml($host,$user,$pass,$database,$tablename,$query){ $link = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error()); $db = mysql_select_db($database, $link) or die(mysql_error()); $result = mysql_query($query); if(!$result){ die('Invalid query: '.mysql_error()); } $numOfCols = mysql_num_fields($result); $numOfRows = mysql_num_rows($result); $info = mysql_fetch_assoc($result); //send headers header('Content-type: text/xml'); header('Pragma: public'); header('Cache-control: private'); header('Expires: -1'); $xml = '<?xml version="1.0" encoding="utf-8"?>'; $xml.= "<{$tablename}>"; if($numOfRows > 0){ do { $xml.= "<row>"; foreach($info as $column => $value) { $xml.= "<{$column}>{$value}</{$column}>"; } $xml.= "</row>"; } while ($info = mysql_fetch_array($result)); } $xml.= "</{$tablename}>"; mysql_free_result($result); return $xml; } http://php.net/manual/en/function.mysql-field-name.php

« previous php.notes (#182479) next »