using <![CDATA in xml response - php

I have looked for an answer to this question but I have been unable to find an answer that works for my application.
I need to give a response from a sql query in xml format but the response is a url so i will need to use cdata. Here is my code.
if ($_POST['action']=="getSermon")
{
//echo"You got it";
$SQL = "SELECT * FROM sermons";
$allsermon = mysql_query($SQL);
$sermonrow = mysql_fetch_assoc($allsermon);
header('Content-type: text/xml; charset=utf-8');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
$xml = '<?xml version="1.0" encoding="utf-8"?>';
echo $xml;
echo "<SERMON_INFO>";
do {
echo "<SERMON>";
echo "<ID>" . $sermonrow['id'] . "</ID>";
echo "<NAME>" . $sermonrow['Name'] . "</NAME>";
echo "<URL>".<![CDATA[$sermonrow['url']]>."</NAME>";
//echo "<URL>". $sermonrow['url'] . "</URL>";
echo "</SERMON>";
mysql_free_result($result);
} while ($sermonrow = mysql_fetch_assoc($allsermon));
mysql_free_result($allsermon);
echo "</SERMON_INFO>";
mysql_close($db);
}
when i do this i get an error 500 and the page will not load.

The correct syntax is
echo "<URL><![CDATA[".$sermonrow['url']."]]></URL>";
But I'd rather you use an XML library like DOMDocument or SimpleXML to build your document, more complex, but you'll be less prone to simple errors like mixing up a closing tag name (see </NAME>).

Related

How to remove space from start of a php file?

Have a PHP file which is making RSS feeds it is giving error because of the space appending before the output XML file. I have checked the code and the variable containing the variable $s which is making XML file does not have any white space before it.
<?php
header("Content-Type: text/xml; encoding=UTF-8");
$s = "<?xml version='1.0' encoding='UTF-8'?><rss version='2.0'><channel>";
echo ltrim($s);
foreach($this->results as $row)
{
$title=$row->name;
$description=$row->description;
echo "<item><title>$title</title><link>$link</link><description>$description</description></item>";
}
echo "</channel></rss>";
?>
Make sure no white space before <?php
<?php
header("Content-Type: text/xml; encoding=UTF-8");
$s = "<?xml version='1.0' encoding='UTF-8'?><rss version='2.0'><channel>";
echo ltrim($s);
foreach($this->results as $row)
{
$title=$row->name;
$description=$row->description;
echo "<item><title>$title</title><link>$link</link><description>$description</description></item>";
}
echo "</channel></rss>";
?>

How to echo <?xml version="1.0" encoding="utf-8"?> in a page?

I'm using a script to display a page in XML, but I need it to display at start but whenever I try, it breaks the code.
Heres the code I tried:
<?php
header('Content-Type: application/xml');
$output = "
<?xml version='1.0' encoding='utf-8' ?>
";
print ($output);
?>
but its not working, any help ?
use echo , Basic Simple XML
<?php
header('Content-Type: application/xml');
$output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo $output;
?>
yes, use echo, but you don't need additional variable and you can use single quote string without backslash...
<?php
header('Content-Type: application/xml');
echo '<?xml version="1.0" encoding="UTF-8"?' . ">\n"; //connate strings to protect end of php formatting in simple editors, and use new line tag
?>

creating XML output in PHP

I am trying to create an XML file output in PHP for a remote phone book on an IP Phone, here is the code i have:
<?php
$conn=mysql_connect("localhost","user","********");
mysql_select_db("db_name",$conn);
header("Content-Type: text/xml");
header("Connection: close");
header("Expires: -1");
?>
<YealinkIPPhoneDirectory>
<?php
$output='<YealinkIPPhoneDirectory>\n';
$sql="SELECT * from contacts ";
$rs=mysql_query($sql,$conn);
while($result=mysql_fetch_array($rs)) {
$output .= "<DirectoryEntry>\n";
$output .= "<Name>Mobile:</Name>\n";
$output .= "<Telephone>" . $result["mobile"] . "</Telephone>\n";
$output .= "</DirectoryEntry>\n";
}
$output='</YealinkIPPhoneDirectory>\n';
echo '$output';
?>
but i get this error message:
This page contains the following errors:
error on line 3 at column 8: Extra content at the end of the document
Below is a rendering of the page up to the first error.
$output
<?php
$conn=mysql_connect("localhost","user","********");
mysql_select_db("db_name",$conn);
header("Content-Type: text/xml");
header("Connection: close");
header("Expires: -1");
$output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$output .= '<YealinkIPPhoneDirectory>\n';
$sql="SELECT * from contacts ";
$rs=mysql_query($sql,$conn);
while($result=mysql_fetch_array($rs)) {
$output .= "<DirectoryEntry>\n";
$output .= "<Name>Mobile:</Name>\n";
$output .= "<Telephone>" . $result["mobile"] . "</Telephone>\n";
$output .= "</DirectoryEntry>\n";
}
$output.='</YealinkIPPhoneDirectory>';
echo $output;
?>
You need to remove this line:
echo '$output';
and replace it with this:
echo $output;
Here is a sample:
https://eval.in/96740
Note how singlequoted values are literally echoed, so you literally see $output as your output.

Dynamically generated XML File Doesn't work on Server but works well on localhost

I generated a XML file in php. This file generates a xml output perfectly in my localhost and at the same time when I uploaded it to my server it fails.
Error Screen
Here is the code.
<?php
include_once("database/db.php");
$sqlNews = "SELECT * FROM news";
$runSqlNews = mysql_query($sqlNews);
while ($rowSqlNews = mysql_fetch_array($runSqlNews))
$arrSqlNews[] = $rowSqlNews;
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<xml>';
for($i=0;$i<count($arrSqlNews);$i++)
{
echo "<news>";
echo "<newsId>".$arrSqlNews[$i][id]."</newsId>";
echo "<newsAuthor>".$arrSqlNews[$i][news_author]."</newsAuthor>";
echo "<description>".$arrSqlNews[$i][news_description]."</description>";
echo "<newsText> <![CDATA[".$arrSqlNews[$i][news_text]. "]]></newsText>";
echo "<plainNewsDescription>".$arrSqlNews[$i][plain_news_description]."</plainNewsDescription>";
echo "<plainNewsTitle>".$arrSqlNews[$i][plain_news_title]."</plainNewsTitle>";
echo "<newsUrl> <![CDATA[". $arrSqlNews[$i][news_url]. "]]></newsUrl>";
echo "<newsCategory> <![CDATA[". $arrSqlNews[$i][category]. "]]></newsCategory>";
echo "<image>http://metroplots.com/images/members/".$arrSqlNews[$i][news_image]."</image>";
echo "<createdOn>".$arrSqlNews[$i][created_on]."</createdOn>";
echo "</news>";
}
echo '</xml>';
?>
New xml File after changes
<?php
ini_set('error_reporting', E_ALL);
include_once("database/db.php");
$dbConn = new mysqli($dbHost, $dbUserName, $dbUserPasswrd, $database);;
$sqlNews = "SELECT id, news_author,news_description,
news_text, news_url, category, news_image, created_on
FROM news";
$stmt = $dbConn->prepare($sqlNews);
$stmt->execute();
$stmt->bind_result($id, $newsAuthor, $newsDescription, $newsText, $newsUrl, $Category, $newsImage, $createdOn);
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<xml>';
echo "<news>";
while($stmt->fetch())
{
echo "<newsId>".$id."</newsId>";
echo "<newsAuthor>".$newsAuthor."</newsAuthor>";
echo "<description>".$newsDescription."</description>";
echo "<newsText> <![CDATA[".$newsText. "]]></newsText>";
echo "<newsUrl> <![CDATA[". $newsUrl. "]]></newsUrl>";
echo "<newsCategory> <![CDATA[". $Category. "]]></newsCategory>";
echo "<image>http://metroplots.com/images/members/".$newsImage."</image>";
echo "<createdOn>".$createdOn."</createdOn>";
}
echo "</news>";
echo '</xml>';
$stmt->close();
$dbConn->close();
?>
Please let me know where I went wrong. Thanks in Advance !!!
Hard to say what exactly goes wrong here.
For debugging, you could add a ini_set('error_reporting', E_ALL); at the beginning of your script or watch your php error log.
You got a few other problems in your script architecture
You should no longer use the mysql extension. Use mysqli or PDO instead.
The headers should be sent once only. Move them out of your loop to the top
why do you loop through the result twice? Remove the for loop and move its content into the while loop. Within the loop replace the variable $arrSqlNews by $rowSqlNews and remove the index accessor [$i]
Simplified example
while( $rowSqlNews = mysqli_fetch_assoc( $mysqliResult ) )
{
echo $rowSqlNews['yourdbCol1'];
}
Have you tried disabling PHP Output Buffering?
In PHP.ini: output_buffering = Off or comment out existing setting: ;output_buffering = On.
Don't forget to restart web server after changing settings.
I suspect that your upload tool transfers the file not in binary-safe way. Try to compare file sizes of the copy on your local machine and the remote one.

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