This question already has answers here:
How to make xml file from php and mysql
(3 answers)
Closed 10 years ago.
I'm using this code to create an XML file (not filed) from a PHP one. Here is the code:
<?php
include_once ('conf.php');
$conn = mysql_connect($host, $user, $password);
if (!$conn) {
die('No hay conexion a la BBDD');
}
$bd = mysql_select_db($name, $conn);
if (!$bd) {
die ('Error en la BBDD');
}
$query = "select * from usuarios where activo = 0 order by puntuacion desc limit 0, 10";
$res = mysql_query($query, $conn);
$salida = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>'."\n";
$salida .= '<score>'."\n";
$i = 1;
while ($row = mysql_fetch_array($res))
{
$salida.= '<posicion num="' . $i . '">'."\n";
$salida .= '<id>'.$row['id'].'</id>'."\n";
$salida .= '<puntuacion>'.$row['puntuacion'].'</puntuacion>'."\n";
$salida .= '</posicion>'."\n";
$i++;
}
$salida .= '</score>';
mysql_free_result($res);
mysql_close($conn);
echo $salida;
?>
When I call this file I obtain (using Chrome Inspector) the XML file embeded in a HTML file with its html, head and body tags. I want this php file to get readed by an ajax's get function.
Any ideas about what is wrong?
Add a header specifying that you're outputting XML. header('Content-Type: text/xml') right before you echo.
Read the PHP manual about XML Manipulation.
You will find juicy tools there to fetch, manipulate and create XML documents.
Also, before making any output, add a line header ("Content-type: text/xml"); to your script, to specify for the client entity, that you are going to send XML and it should be parsed as XML. header — Send a raw HTTP header
Related
Hi so I need to populate an array in flash with information from php. My php code is :
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
}
$db_select = mysql_select_db("profileofperson",$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
}
?>
<html>
<head>
<title>mySQLtestfile</title>
</head>
<body>
<?php
//Step4
$result = mysql_query("SELECT * FROM catalogue", $db);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row[" Name"]." ".$row["age"]." ".$row["Allergies"]." ".$row["height"]." ".$row["weight"]."<br />";
}
?>
</body>
</html>
which at present is displaying information from a database. How do i get flash to populate into an array?
Make your document xml, not html, start the document like this:
<?php
header("Content-type: text/xml");
echo chr(60).chr(63).'xml version="1.0" encoding="utf-8" '.chr(63).chr(62);
This just adds a header tag so the browser/flash recognises the document as XML (similar to !DOCTYPE with HTML) : <?xml version="1.0" encoding="UTF-8"?>
Then, query as you are doing, but echo the results in a valid XML format:
echo "<people>";//Create the parent node
while ($row = mysql_fetch_array($result)) {
echo "<person>";//Open child node, add values:
echo "<name>".$row[" Name"]."</name>";
echo "<age>".$row["age"]."</age>";
echo "<allergies>".$row["Allergies"]."</allergies>";
echo "<height>".$row["height"]."</height>";
echo "<weight>".$row["weight"]."</weight>";
echo "</person>";//Close child node
};
echo "</people>";//Close the parent node
?>
I've just written this out off the top of my head so may not be perfect, but it should be easy enough for you to check that it's generating a valid XML document (just load the page in a browser, get an XML viewer plugin to find out more if it's going wrong) and adjust if not, there are millions of tutorials on generating XML pages from PHP.
Then, use the URLLoader class in your flash application to access it:
var loader:URLLoader = new URLLoader();
//The loader class
var urlRQ:URLRequest = new URLRequest('yoursite/yourpage');
//The URL request
loader.dataFormat = URLLoaderDataFormat.TEXT;
//Use this for xml
urlRQ.method = URLRequestMethod.POST;
//Set method type (normally post)
loader.load(urlRQ);
loader.addEventListener(Event.COMPLETE,loadedData);
Then, have loadedData parse the XML:
function loadedData(e:Event):void {
var people:XML = XML(e.target.data);//Cast this var as XML to access
//people should represent top-level ie <people>;
for each(var person:XML in people.person){//Iterate over member nodes called 'person';
trace(person.age);//XML object node names can be referenced
//directly with dot notation!
trace(person.name);//etc...
}
}
One last thing, the mysql_ functions are deprecated in PHP, I found this out recently, use SQLi or PDO instead in future!
Hope this helps, as I say I've written it off the top of my head and it's better that you experiment with it, but if you do get stuck leave a comment and I'll have a look!
I have no idea of what is going wrong, i was using this same script to get another XML and it was working just fine.
This is the script:
<?php
header("Content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"LATIN-1\"?>";
echo "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">";
echo "<plist version=\"1.0\">";
function getXML($sql="SELECT IDCargo FROM database.table"){
$conn = mysql_connect ("myserverurl.com", "user", "psw");
$db = mysql_select_db("database");
$result = mysql_query($sql, $conn);
$column = "";
echo "<array>";
while($row = mysql_fetch_assoc($result)){
$column .= "<dict>";
foreach ($row as $key => $value){
$column .= "<key>$key</key>";
$column .= "<string>$value</string>";
}
$column .= "</dict>";
}
echo $column;
echo "</array>";
echo "</plist>";
}
getXML("SELECT IDCargo as ID_CARGO, SequencialDoCandidato as NUMERO_SEQ_CANDIDATO, NomeDoCandidato AS NOME_CANDIDATO, NumeroDoCandidato as NUMERO_CANDIDATO, NomeDoPartido AS SIGLA_PARTIDO, Estado as SIGLA_ESTADO,IDUnidadeEleitoral AS ID_CIDADE_CANDIDATO, UnidadeEleitoral AS CIDADE_CANDIDATO FROM database.table");
mysql_close();
?>
It brings this error:
This page contains the following errors:
error on line 1 at column 538: Encoding error
Below is a rendering of the page up to the first error.
ID_CARGO11NUMERO_SEQ_CANDIDATO10000002965NOME_CANDIDATOAGRECINO DE SOUSANUMERO_CANDIDATO13SIGLA_PARTIDOPTSIGLA_ESTADOACID_CIDADE_CANDIDATO1120CIDADE_CANDIDATO
Can anyone see anything? Give me some help here, please.
I got the script from one that was working just fine.
If I read your code, I can see :
echo "<?xml version=\"1.0\" encoding=\"LATIN-1\"?>";
So I guess you want to output LATIN-1 charset. You need to specify this charset everywhere :
1/ You can try to specify the encoding on the http header :
header("Content-type: text/xml; charset=ISO-8859-1");
2/ And you can also set the charset on the DB client :
mysql_set_charset('latin1', $db);
Your output most likely contains a character or characters in an encoding not supported in the default encoding.
Either update the encoding you use, or escape any characters that does not fit the encoding. The htmlentities php function would be a good start.
I am trying to load in XML to populate a search box. The code I have works fine with a static xml file, but I need to load in a PHP file to generate a dynamic XML file based on data from a database.
I knwo the PHP file generates the XML as it loads in a browser and the page source shows the correct nodes etc, however when I reference the .php file in my JavaScript it fails to load, or show an error... Using the .xml file (which is a replica of the php output source) it loads fine.
I would like someone to check to see if I am encoding the XML correctly or missing something in my JavaScript... and advice will be greatly appreciated.
JS
var myArr = [];
$.ajax({
url: "people.php", // change to full path of file on server
type: "GET",
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function(data) {
alert("XML File could not be found");
}
});
function parseXml(xml){
$(xml).find("person").each(function(){
var thisItem = $(this).find('name').text();
myArr.push(thisItem);
alert(thisItem);
});
}
PHP
<?php
include '../../inc_global/connect.php';
$query = 'SELECT * FROM candidates';
$result = mysql_query($query, $link);
$xmlOutput = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xmlOutput .= "<people>\n";
while ($line = mysql_fetch_assoc($result)) {
$xmlOutput .= "<person>\n";
$xmlOutput .= "<name>" . $line['name'] . "</name>\n";
$xmlOutput .= "</person>\n";
}
$xmlOutput .= "</people>\n";
echo $xmlOutput;
mysql_close($link);
?>
Try to put header right before outputting information:
....
header ("Content-Type:text/xml");
echo $xmlOutput;
....
Fullcode:
<?php
include '../../inc_global/connect.php';
$query = 'SELECT * FROM candidates';
$result = mysql_query($query, $link);
$xmlOutput = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xmlOutput .= "<people>\n";
while ($line = mysql_fetch_assoc($result)) {
$xmlOutput .= "<person>\n";
$xmlOutput .= "<name>" . $line['name'] . "</name>\n";
$xmlOutput .= "</person>\n";
}
$xmlOutput .= "</people>\n";
header ("Content-Type:text/xml"); //<----------- xml header here
echo $xmlOutput;
mysql_close($link);
?>
Check what's happening in php pointing your browser to people.php.
Anyway I advice you to:
drop mysql_ for PDO
As mysql_ funcs are bad and will prevent from meeting chicks, while PDO helps;
use SimpleXML against raw XML
SimpleXML helps you structure your code without getting mad in chaining strings.
give proper HTTP header to your document
You are generating an XML document, let the browser be aware of that:
header ("Content-Type:text/xml");
echo $xmlOutput;
Can you make sure that the function parseXml(xml) doesn't need any parameter when it is called on success of ajax call. Please note that I haven't tried the code but just a guess is here.
I am developing an iPhone app and I want to put some datas to UITableView.
I got an app showing several xml parser run from here.
and then, I'd separated GDataXMLParser from this project and made it run but
I have an odd problem that I can't figure out.
This is the code putting php file.
- (void)start {
self.startTimeReference = [NSDate timeIntervalSinceReferenceDate];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
self.parsedSongs = [NSMutableArray array];
NSURL *url = [NSURL URLWithString:#"http://mydomain.blabla/phpxmltest.php"];
[NSThread detachNewThreadSelector:#selector(downloadAndParse:) toTarget:self withObject:url];
}
When I make a php to xml with echo directly, like this way,
......
echo "<entry><title>this is the TEST</title><item>TEST</item></entry>";
......
iPhone app does parse this code like XML.
But when I make a php to xml with mySQL query (cause I want to make a xml items from DB), like this way,
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>';
$result = mysql_connect("localhost", "my ID", "my Password");
mysql_select_db("my DB");
$q = "select name, price, age, likeit, keyword from Table where category=101";
$result = mysql_query($q);
$num_rows = mysql_num_rows($result);
echo "<entry>\n";
for ($i=1; $i<=$num_rows; $i++) {
$row = mysql_fetch_assoc($result);
echo "<item>\n";
echo "<title>" . $row["name"] . "</title>\n";
echo "<category>" . $row["price"] . "</category>\n";
echo "<artist>" . $row["age"] . "</artist>\n";
echo "<album>" . $row["likeit"] . "</album>\n";
echo "<releasedate>" . $row["keyword"] . "</releasedate>\n";
echo "</item>\n";
}
echo "</entry>";
?>
iPhone app doesn't parse this code. It tells me there's no item in XML.
What is the most strange to me, is the results on Web Browser are same exactly.
When I put the url in browser, the output itself and the source(with viewing source function of browser) are exactly same. This is the source view in web browser.(Plz don't mind some encoding problem)
<?xml version="1.0" encoding="UTF-8"?>
<entry>
<item>
<title>������ ���ĺ� ������</title>
<category>11000</category>
<artist>3</artist>
<album>0</album>
<releasedate>���ĺ� ���߱�</releasedate>
</item>
<item>
<title>���ĺ� ��������</title>
<category>18000</category>
<artist>3</artist>
<album>0</album>
<releasedate>���ĺ� ����</releasedate>
</item>
…..
I've tried hard to make it work but it's too difficult for me. I am a starter in iOS and Web Programming. Please let me know what is the problem and solution.
Thank u in advance!:D
(Plz don't mind some encoding problem)Maybe we don't mind but the xml parser probably does.
You should
set the mimetype in the http response header
set the charset in the http response header (though it's already in the xml declaration)
set mysql's client encondig to utf8 in order to receive the data utf-8 encoded
treat all the data from the database with an appropriate escape function
or even better use something like XMLWriter
and you should also print error messages as a somewhat valid xml document since you told the client that it will receive xml.
E.g. (tested only by php -l):
<?php
if ( headers_sent() ) {
die("can't set mimetype and/or charset after output has been sent to the client");
}
ini_set('default_charset', 'utf-8');
ini_set('default_mimetype', 'text/xml');
// ini_set('default_mimetype', 'application/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
$mysql = mysql_connect("localhost", "my ID", "my Password");
if ( !$mysql ) {
die('<error>database connection failed</error>');
}
if ( !mysql_select_db("my DB", $mysql) ) {
die('<error>database selection failed</error>');
}
if ( !mysql_set_charset('utf8', $mysql) ) {
die('<error>setting database selectiocharset failed</error>');
}
$q = 'SELECT name, price, age, likeit, keyword FROM Table WHERE category=101';
$result = mysql_query($q, $mysql);
if ( !$result ) {
die('<error>database query failed</error>');
}
echo "<entry>\n";
while( false!=($row=mysql_fetch_assoc($result)) ) {
echo '
<item>
<title>', htmlspecialchars($row["name"], 'utf-8'), '</title>
<category>', htmlspecialchars($row["price"], 'utf-8'), '</category>
<artist>', htmlspecialchars($row["age"], 'utf-8'), '</artist>
<album>', htmlspecialchars($row["likeit"], 'utf-8'), '"</album>
<releasedate>', htmlspecialchars($row["keyword"], 'utf-8'), '</releasedate>
</item>';
}
echo "</entry>";
?>
This question already has answers here:
Output raw XML using php
(5 answers)
Closed 3 years ago.
I am trying to display xml in browser.i have created a xml like
$query2 = "SELECT * FROM user where user_id = 7";
$dbresult = mysqli_query($dbcon,$query2) or die('query error...');
$doc = new DomDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('root');
$root = $doc->appendChild($root);
while($row = mysqli_fetch_array($dbresult)) {
$userId = $doc->createElement('UserId');
$userId = $root->appendChild($userId);
$value = $doc->createTextNode($row[0]);
$value = $userId->appendChild($value);
$psw = $doc->createElement('Password');
$psw = $root->appendChild($psw);
$value = $doc->createTextNode($row[2]);
$value = $psw->appendChild($value);
}
echo $doc->saveXML();
$doc->save("test.xml");
it displaying just data like
7 pwd123
but i want data like
<xml>
<root>
<userId>7</userId>
<password>pwd123</password>
</root>
</xml>
what to do for that?
thanks
Your script doesn't set the Content-type header and php sends the default content-type header which usually is Content-type: text/html.
The client therefore assumes that the data is an html document and parses and displays it as such.
And if the client/browser doesn't "know" the tags/elements your document contains (and context matters) http://www.w3.org/TR/html401/appendix/notes.html#notes-invalid-docs applies.
If you "tell" the client that the output is an xml document it will/can/should display it accordingly.
if ( headers_sent() ) {
// can't set the content-type after output has been sent to the client
die('error');
}
else {
header('Content-type: text/xml'); // see http://en.wikipedia.org/wiki/XML_and_MIME
echo $doc->saveXML();
}
Change your header content-type text/xml
header('Content-type: text/xml');
$doc->saveXML();
For more details refer http://www.w3schools.com/xml/xml_server.asp
use Right Click -> Show source code command