XML(in php) parsing on iPhone - php

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>";
?>

Related

Need to remove headers from cURL XML response in PHP

There's a few threads about this, but I couldn't find a solution to this issue in them. I hope it doesn't violate duplicate rules.
I've tested the following code with static XML and it works great, but said XML did not contain any headers.
I'm trying to remove headers through code after making a POST request so I can continue to process the resulting XML, but I'm not having any luck with it.
This is the XML:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><AUTOS_Cotizar_PHPResponse xmlns="http://tempuri.org/"><AUTOS_Cotizar_PHPResult><auto xmlns=""><operacion>1555843</operacion><statusSuccess>TRUE</statusSuccess><statusText></statusText><cotizacion><cobertura><codigo>A0</codigo><descripcion>RESPONSABILIDAD CIVIL SOLAMENTE</descripcion><premio>928,45</premio><cuotas>01</cuotas><impcuotas>928,45</impcuotas></cobertura></cotizacion><datos_cotiz><suma>477250</suma><uso>901</uso></datos_cotiz></auto></AUTOS_Cotizar_PHPResult></AUTOS_Cotizar_PHPResponse></soap:Body></soap:Envelope>
this is the code:
//converting raw cURL response to XML
$temp1 = htmlspecialchars ($reply);
//replacing top headers
$temp2 = str_replace('<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><AUTOS_Cotizar_PHPResponse xmlns="http://tempuri.org/"><AUTOS_Cotizar_PHPResult>', "<<<'EOD'", $temp1);
//replacing closing header tags
$temp3 = str_replace('</AUTOS_Cotizar_PHPResult></AUTOS_Cotizar_PHPResponse></soap:Body></soap:Envelope>', "EOD;", $temp2);
//this returns the original $temp1 without having anything replaced
echo $temp3;
//simplexml conversion
$xml = simplexml_load_string($temp3);
//running through the array and printing all values
if ($xml !== false) {
foreach ($xml->cotizacion as $cotizacion) {
foreach ($cotizacion->cobertura as $cobertura) {
echo $cobertura->codigo;
echo '<br>';
echo $cobertura->descripcion;
echo '<br>';
echo $cobertura->premio;
echo '<br>';
echo $cobertura->cuotas;
echo '<br>';
echo $cobertura->impcuotas;
echo '<br>';
}
}
}
There are probably more efficient ways to do this, or maybe I'm not doing this correctly. I'm just about learning right now, so feel free to correct me in any way if you want, I'd appreciate it!
The way you are processing the response string is a bad idea, you should stick to processing the content as XML and work with it. This uses XPath to find a start point to process the data (which I can't test with the current sample), but should help with what you need to do...
// Load the original reply
$xml = simplexml_load_string($reply);
//running through the array and printing all values
if ($xml !== false) {
// Find the <auto> element (use [0] as you want the first one)
$auto = $xml->xpath("//auto")[0];
// Loop through the cotizacion elements in the auto element
foreach ($auto->cotizacion as $cotizacion) {
foreach ($cotizacion->cobertura as $cobertura) {
echo $cobertura->codigo;
echo '<br>';
echo $cobertura->descripcion;
echo '<br>';
echo $cobertura->premio;
echo '<br>';
echo $cobertura->cuotas;
echo '<br>';
echo $cobertura->impcuotas;
echo '<br>';
}
}
}
The SOAP response is still an XML document, so work with it instead of fighting it. Treating it as a string is definitely not great.
As far as I can tell you're trying to work with all the <cotizaction> elements. It's simple to find elements inside an XML document. Read up on XPath.
$xml = simplexml_load_string(htmlspecialchars($reply));
if ($xml) {
foreach ($xml->xpath('//cotizacion') as $cotizacion) {
// do your thing
}
}

Converting MySQL rows to XML with PHP

I'm working on my php script to output the information from mysql database. I want to output these echo results in my php page as a xml file as i want to make it looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.mysite.com/xmltv">
<channel id="">
<display-name></display-name>
<programme channel="" start="" stop="">
<title lang="en"></title>
<sub-title lang="en"></sub-title>
<desc lang="en"></desc>
<category lang="en"></category>
</programme>
</channel>
Here's my PHP:
<?php
function db_connect()
{
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypasword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
}
db_connect();
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = clean($_GET['channels']);
$id = clean($_GET['id']);
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
zap2it($row);
}
mysql_close();
}
else if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
echo '<?xml version=""1.0"" encoding="UTF-8" ?>';
echo '<tv generator-info-name="www.mysite.com/xmltv">';
echo '<channel id="">';
echo '<display-name></display-name>';
echo '<programme channel="" start="" stop="">';
echo '<title lang="en"></title>';
echo '<sub-title lang="en"></sub-title>';
echo '<desc lang="en"></desc>';
echo '<category lang="en"></category>';
echo '</programme>';
echo '</channel>';
while ($row = mysql_fetch_array($result1))
{
echo "<p id='channels'>".$row["id"]. " " . $row["channels"]. "</p>";
echo "<p id='links'>";
echo "http://www.mysite.com/get-listing.php?channels=" . $row["channels"] . "&id=" . $row["id"] .'</p>';
}
}
}
?>
Here's what my php output looks like:
<?xml version="1.0" encoding="UTF-8" ?><tv generator-info-name="www.mysite.com/xmltv"><channel id=""><display-name></display-name><programme channel="" start="" stop=""><title lang="en"></title><sub-title lang="en"></sub-title><desc lang="en"></desc><category lang="en"></category></programme></channel>
Edit: I have got a problem with echo. I can't be able to echo for the channels in the database.
if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
}
mysql_close();
}
Here's the error I have got: error on line 12 at column 11: XML declaration allowed only at the start of the document
I will get the error when I'm using this under the while statement:
while ($row = mysql_fetch_array($result1))
{
echo '<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.mysite.com/xmltv">
<channel id="">
<display-name></display-name>
<programme channel="" start="" stop="">
<title lang="en"></title>
<sub-title lang="en"></sub-title>
<desc lang="en"></desc>
<category lang="en"></category>
</programme>
</channel>
</tv>';
}
The output for my php is show as blank page. How do you use the code to allow me to print these xml output in my php?
if channel = 0 and id = 0 your output is correct. It may not be tabbed, but it is correct to your logic.
Depending on the browser XML might show a blank page ... make sure you do view code!
You need to rethink your logic though $channel && $id and then do !$channel && !id is suspiciously odd.
It looks like you are already successfully generating XML. Your problem is that it shows up as a blank page. This is expected, because your web browser is going to interpret the XML as a bunch of HTML tags, and tags don't get displayed.
What you probably want to do is set the content type to XML so that the web browser knows it's XML and not HTML. You can do this by adding the header before you send any other output (i.e. before any echo statements):
header('Content-type: application/xml');
This is necessary because if you don't specify the content type explicitly, the server will automatically send a content type header that tells the browser that the content is HTML.
You can use your browser's debugging console (press F12 to open it in most modern browsers) to inspect the HTTP headers that your script is sending and verify that it's declaring the correct content type.
The other alternative is to format the XML as HTML. This probably isn't really desirable, because the purpose of XML is the be processed by some other client and turning it into HTML makes it useless. However, if you really want to, it can be done by putting all the XML in a string and then calling the htmlspecialchars function to format it as HTML. (This turns the < and > into HTML entities, causing them to be displayed in your browser.)

Populate an array in flash with data from php

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!

Creating XML File from PHP but get HTML one [duplicate]

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

PHP Script not Working: error on line 1 column 538

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.

Categories