PHP load as XML in JQuery - php

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.

Related

When posting data containing the text "or #"|| "and #" to PHP from AJAX $_REQUEST Blows up with "Error 403 Forbidden"

I have a workaround for this problem but can't for the life of me determine if the problem is in my AJAX or PHP code or if I am just missing something.
I have included the source code that creates an RSS XML feed document. I first create an Object array to store the keyed data that will be supplied to AJAX and then call the PHP script which creates the feed document. Works perfectly with the following strange boolean operator word exceptions.
1. If any keyed data contains the word 'or' followed by a space followed by any number then the PHP script blows up with error 403 when trying to access $_REQUEST or $_POST variables.
2. If any keyed data contains the word 'and' followed by a space followed by any number then the PHP script blows up with error 403 when trying to access $_REQUEST or $_POST variables.
Here is my code:
ajax_or_php_bug_main.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax or PHP Bug</title>
<!--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax_or_php_bug.js"></script>
</head>
<body>
<div class="center_form">
<form class="rss_form" method="post">
<label class="disp">Title: </label><input class="rss_channel_title" type="text" value="" placeholder="Enter a title for this feed" /><br/>
<label class="disp">Subtitle: </label><input class="rss_channel_subtitle" type="text" value="" placeholder="Enter a subtitle for this feed" /><br/>
<label class="disp">Item Description Lines: </label><textarea class="rss_item_text"></textarea><br/>
<input class="save_button" type="button" value="Save RSS Feed" />
</form>
</div>
</body>
</html>
ajax_or_php_bug.js
$(function (){
var feedFilename = 'myfeed.xml';
$('.rss_channel_title').val('My Channel Title');
$('.rss_channel_subtitle').val('My Channel Subtitle');
$('.rss_item_text').val('or 9');
////////////////////////////////////////////////////////////
// SAVE RSS FEED
////////////////////////////////////////////////////////////
$(".save_button").on('click', function(){
var jsonData=createJSONArray();
$.ajax({
type: "POST",
url: "rss_save_feed.php",
data: {feedarray: jsonData},
/*data: "feedarray="+jsonData,*/
datatype: "json",
/*traditional: true,*/
success: function(feed_text){
alert('RETURNED FROM SAVE PHP: '+feed_text);
},
beforeSend:function()
{
}
});
return false;
});
////////////////////////////////////////////////////////////
// Create Array of Aruments
////////////////////////////////////////////////////////////
function createJSONArray() {
//alert('in createJSONArray');
var returnObj = new Object();
returnObj.filename = feedFilename;
returnObj.title = $('.rss_channel_title').val();
returnObj.subtitle = $('.rss_channel_subtitle').val();
items = $('.rss_item_text').val();
//items = items.replace(/or/g,"0987654321"); //UNCOMMENT FOR WORKAROUND
//items = items.replace(/and/g,"1234567890"); //UNCOMMENT FOR WORKAROUND
returnObj.items = items;
return returnObj;
}
});
rss_save_feed.php
<?php
if(!isset($_REQUEST)){
die('Too bad!');
}
//this next line blows with "Error 403 Forbidden" if data contains "or #"||"and #"
//it doesn't matter if the data is an array, xml or text being passed
//not sure if the problem is related to ajax or php???
$args = $_REQUEST['feedarray'];
if($args){
//Create the RSS Feed
$rss = '';
$rss .= '<?xml version="1.0" encoding="utf-8"?>';
$rss .= '<?xml-stylesheet type="text/xsl"?>';
$rss .= '<rss version="2.0">';
$rss .= '<channel>';
$rss .= '<title>' . $args[title] . '</title>';
$rss .= '<description>' . $args[subtitle] . '</description>';
$rss .= '<pubDate>' . date(DATE_RSS, strtotime("now")) . '</pubDate>';
$rss .= '<location>' . $args[location] . '</location>';
$items = $args[items];
//$items = str_replace("0987654321","or",$items); //UNCOMMENT FOR WORKAROUND
//$items = str_replace("1234567890","and",$items); //UNCOMMENT FOR WORKAROUND
$items = explode("\n",$items);
foreach($items as $item){
$rss .= '<item>';
$rss .= '<description>' . $item . '</description>';
$rss .= '<pubDate>' . date(DATE_RSS, strtotime("now")) . '</pubDate>';
$rss .= '</item>';
}
$rss .= '</channel>';
$rss .= '</rss>';
//file_put_contents($args[filename], $rss);
echo $rss;
}
?>
This is very likely some kind of security module/filter on your web server. What web server are you using? I saw similar problems with IIS and I know there is filter module for nginx. So just check the web server logs.
In ajax_or_php_bug.js replace
items = items.replace(/or/g,"0987654321");
items = items.replace(/and/g,"1234567890");
with this
items = items.replace("/or/g","0987654321");
items = items.replace("/and/g","1234567890");
I just had this same exact problem happen on my websites hosted by HTTPME.com. I don't suppose you're using the same web host? I just opened up a ticket with them asking them to whitelist my websites (or whatever they need to do) because I already have logic in my PHP code to remove any potentially dangerous logic that a user might try to inject. I had to open up a ticket a couple of months ago for the same sort of thing when I discovered that I could no longer use the word 'exit' (or any words that have the word 'exit' embedded in the larger word) in any of my web forms. At the time, they told me that it was being triggered by a ModSecurity rule.

PHP output doesn't print in xml format

i have the following code.
$stmt = $conn->prepare('SELECT sponsor_path FROM sponsors WHERE conference_id = ?');
$stmt->execute(array($cid));
$sponsorsImg = $stmt->fetchall (PDO::FETCH_OBJ);
$xml_output = "<?xml version=\"1.0\" ?>";
$xml_output .= "<sponsors>";
foreach ($sponsorsImg as $spImg){
$xml_output .= "<sponsor>\n";
$xml_output .= "<image>".$spImg->sponsor_path."</image>\n";
$xml_output .= "</sponsor>\n";
}
$xml_output .= "</sponsors>";
echo $xml_output;
Instead of printing the results in xml format i get only the $spImg->sponsor_path's content in plain text. Any ideas?
Most browsers will render markup that looks like XML. So it might be the case that the XML that you want is actually produced but not displayed correctly on the browser.
Try the following:
Set the content type before outputting:
header('Content-Type: text/xml');
echo $xml_output;
If the output looks the same, then right click on the page and select view source. You should see your XML markup as intended there.

PHP - generate & store xml as string in a variable

I'm trying to store a xml as string in a variable so that I can store it in my database.
$xml = "<root>";
foreach(...){
$xml .= "<user id='$id'/>";
}
$xml .= "</root>";
When I echo it, it's not displayed at all as if my web brower reads it as html tag. It doesn't even look like $xml is storing those as texts. Now, I'm trying to do it with DOMDocument... not not quite successful yet. Any tips? :(
Edited my stupid += mistakes..
PHP uses a . as a concatenate operator, or a .= as a shortcut, not a + or +=.
$xml = "<root>";
foreach(...){
$xml .= "<user id='$id'/>";
}
$xml .= "</root>";

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