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.
Related
My problem is that the accents are not displayed in the output of print_r().
Here is my code:
<?php
include('./lib/simple_html_dom.php');
error_reporting(E_ALL);
if (isset($_GET['q'])){
$q = $_GET['q'];
$keyword=urlencode($q);
$url="https://www.google.com/search?q=$keyword";
$html=file_get_html($url);
$results=$html->find('li.g');
$G_tot = sizeof($results)-1;
for($g=0;$g<=$G_tot;$g++){
$results=$html->find('li.g',$g);
$array_ttl_google[]=$results->find('h3.r',0)->plaintext;
$array_desc_google[]=$results->find('span.st',0)->plaintext;
$array_href_google[]=$results->find('cite',0)->plaintext;
}
print_r($array_desc_google);
}
?>
Here is the result of print_r:
Array ( [0] => �t� m (plural �t�s)...
What is the resolution in your opinion?
3 basic things you can do:
Set the page encoding to UTF-8 - Add at the very begining of your page: header('Content-Type: text/html; charset=utf-8');
Make sure your code file is saved as UTF-8 (without BOM).
Add a function to translate the parsed string to UTF-8 (in case some other sites are using different encodings)
Your code should look something like that (Tested - working great tried with english and hebrew results):
<?php
header('Content-Type: text/html; charset=utf-8');
include('simple_html_dom.php');
error_reporting(0);
if (isset($_GET['q'])){
$q = $_GET['q'];
$keyword=urlencode($q);
$url="https://www.google.com/search?q=$keyword";
$html=file_get_html($url);
//Make sure we received UTF-8:
$encoding = #mb_detect_encoding($html);
if ($encoding && strtoupper($encoding) != "UTF-8")
$html = #iconv($encoding, "utf-8//TRANSLIT//IGNORE", $html);
//Proceed with your code:
$results=$html->find('li.g');
$G_tot = sizeof($results)-1;
for($g=0;$g<=$G_tot;$g++){
$results=$html->find('li.g',$g);
$array_ttl_google[]= $results->find('h3.r',0)->plaintext;
$array_desc_google[]= $results->find('span.st',0)->plaintext;
$array_href_google[] = $results->find('cite',0)->plaintext;
}
print_r($array_desc_google);
} else {
echo "You forgot to set the 'q' variable in your url.";
}
?>
i'm trying to print a JSON in Hebrew and only get utf-8 encoded string. how can I make sure the client's browser shows the string in Hebrew?
the code is:
<html>
<head>
<meta charset=utf-8" />
</head>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$response = array();
require_once __DIR__.'/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query(" SELECT * FROM stores") or die(mysql_error());
if (mysql_num_rows($result)>0){
$response["stores"]=array();
while($row = mysql_fetch_array($result)){
$store = array();
$store["_id"]=$row["_id"];
$store["name"]=$row["name"];
$store["store_type"]=$row["store_type"];
array_push($response["stores"],$store);
}
$response["success"] = 1;
$string = utf8_encode(json_encode($response));
echo hebrevc($string);
}else{
$response["success"]=0;
$response["message"]="No stores found";
echo utf8_encode(json_encode($response));
}
?>
</body>
</html>
and the response is:
{{"stores":[{"_id":"1","name":"\u05d7\u05ea\u05d5\u05dc\u05d9","store_type":"\u05de\u05e1\u05e2\u05d3\u05ea \u05d1\u05e9\u05e8\u05d9\u05dd"},{"_id":"2","name":"\u05de\u05e2\u05d3\u05e0\u05d9 \u05de\u05d0\u05de\u05d9","store_type":"\u05de\u05e1\u05e2\u05d3\u05d4 \u05dc\u05e8\u05d5\u05e1\u05d9\u05dd"}],"success":1
A nice constant was added in PHP 5.4: JSON_UNESCAPED_UNICODE
Using it will not escape your Hebrew characters.
echo json_encode($response, JSON_UNESCAPED_UNICODE);
Check out the json_encode reference.
The result looks like a UCS-2 string. Try setting the charset of the Mysql Connection:
mysql_set_charset('utf8', $conn)
then remove the utf8_encode statements
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
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>";
?>