Data not saved properly into XML file - php

I am trying to save data to a XML file.
if (isset( $_POST['submit'])) {
$name = mysql_real_escape_string($_POST['name']);
$xml = new DOMDocument("1.0", "ISO-8859-1");
$xml->preserveWhiteSpace = false;
$xml->load('/var/www/Report/file.xml');
$element = $xml->getElementsByTagName('entries');
$newItem = $xml->createElement('reports');
$newItem->appendChild($xml->createElement('timestamp', date("F j, Y, g:i a",time())));
$newItem->appendChild($xml->createElement('name', $name));
$element -> item(0) -> appendChild($newItem);
$xml->formatOutput = true; // this adds spaces, new lines and makes the XML more readable format.
$xmlString = $xml->saveXML(); // $xmlString contains the entire String
$xml->save('/var/www/Report/file.xml');
}
Anytime I use mysql_real_escape_string() to escapes special characters in my string or try to to sanitize my data, my XML file looks like something in the image below.
I don't understand why the name start tag is missing in my XML file and why my data $name isn't saved into the XML file either. How could I to fix this. Any help would be appreciated. Thanks in advance

1) Firefox does not show the xml byte-by-byte, rather it formats it itself. Therefore empty elements appear with only one self closing tag, no matter how they appear in the xml source. If you want to see the exact xml output, then open it in a text editor.
2) mysql_real_escape_string escapes characters that are problematic for mysql, not for XML: for example it does not escape '<'. Instead it, you should use DOMDocument::createTextNode. So instead of
$newItem->appendChild($xml->createElement('name', $name));
use
$nameElement = $xml->createElement('name');
$nameElement->appendChild( $xml->createTextNode($name) );
$newItem->appendChild($nameElement);
3) As you see, the $name is empty, but I don't know what can be the problem with your POST data seeing only this code, maybe there is no <input name='name' /> in your form: I sometimes accidentally set an id attribute to inputs instead of the name attribute.

Related

Modify CDATA String and insert again in CDATA format?

Actual I have one problem. I want to append something to string in CDATA format in a XML file.
<url><![CDATA[http://www.kinguin.net/category/1356/l-a-noire-steam-key/?nosalesbooster=1&country_store=1&currency=EUR]]</url>
After I modify the string with this code:
$doc = simplexml_import_dom($dom);
$items = $doc->xpath('//url');
foreach ($items as $item) {
$node = dom_import_simplexml($item);
$node->textContent .= 'appendIT';
}
I get:
<url>http://www.kinguin.net/category/1356/l-a-noire-steam-key/?nosalesbooster=1&country_store=1&currency=EURappendIT]]</url>
But how can I say "Put it back into the CDATA format"?
And in addition. I want to send this url to my database. But without the & char. So how can I get the url without the &?
Greetings and Thank You!
As CDATA in XML stands for "character data", you can treat it as a string without parsing it. CDATA ends with ]] (assume not nested CDATA), so
$xmlstrIn = '<url><![CDATA[http://www.kinguin.net/category/1356/l-a-noire-steam-key/?nosalesbooster=1&country_store=1&currency=EUR]]</url>';
$xmlstrOut = preg_replace('|(\]\])|', 'appendIT$1', $xmlstrIn);
and send $xmlstrOut to your database.
Hope this solves the problem (unless you are doing research of SimpleXML extension or something).
Regards,
Nick

PHP decoding square brackets href attr to html file

Saving an html the decodes square brackets.
//My STRing
$teaserTest = "<a href='[CLICK_URL]'><strong>testgerr</strong></a>";
//Calling save function
saveFile($teaserTest);
//Save function
function saveFile($stringToAdd){
$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->loadHTML('<html><head><title>Test</title></head><body>'.$stringToAdd.'</body></html>');
$doc->saveHTMLFile("Campaigns/test.html");
}
file resaults <a href="%5BCLICK_URL%5D">
im trying to keep the"[" decoded.
[] brackets are special chars in url
which is specified in following RFC It is important for the ip address for example: http://[::1]/example/
That because it is good to encoding. But if you have a special approach use a different pattern for it.

PHP: Converting xml to array

I have an xml string. That xml string has to be converted into PHP array in order to be processed by other parts of software my team is working on.
For xml -> array conversion i'm using something like this:
if(get_class($xmlString) != 'SimpleXMLElement') {
$xml = simplexml_load_string($xmlString);
}
if(!$xml) {
return false;
}
It works fine - most of the time :) The problem arises when my "xmlString" contains something like this:
<Line0 User="-5" ID="7436194"><Node0 Key="<1" Value="0"></Node0></Line0>
Then, simplexml_load_string won't do it's job (and i know that's because of character "<").
As i can't influence any other part of the code (i can't open up a module that's generating XML string and tell it "encode special characters, please!") i need your suggestions on how to fix that problem BEFORE calling "simplexml_load_string".
Do you have some ideas? I've tried
str_replace("<","<",$xmlString)
but, that simply ruins entire "xmlString"... :(
Well, then you can just replace the special characters in the $xmlString to the HTML entity counterparts using htmlspecialchars() and preg_replace_callback().
I know this is not performance friendly, but it does the job :)
<?php
$xmlString = '<Line0 User="-5" ID="7436194"><Node0 Key="<1" Value="0"></Node0></Line0>';
$xmlString = preg_replace_callback('~(?:").*?(?:")~',
function ($matches) {
return htmlspecialchars($matches[0], ENT_NOQUOTES);
},
$xmlString
);
header('Content-Type: text/plain');
echo $xmlString; // you will see the special characters are converted to HTML entities :)
echo PHP_EOL . PHP_EOL; // tidy :)
$xmlobj = simplexml_load_string($xmlString);
var_dump($xmlobj);
?>

XML character encoding issue with PHP

I have code which is creating an XML, my only problem is with the encoding of words like á, olá and ção.
These characters dont appear correctly and when I try reading the XML I get an error displayed relating to that character.
$dom_doc = new DOMDocument("1.0", "utf-8");
$dom_doc->preserveWhiteSpace = false;
$dom_doc->formatOutput = true;
$element = $dom->createElement("hotels");
while ($row = mysql_fetch_assoc($result)) {
$contact = $dom_doc->createElement( "m" . $row['id'] );
$nome = $dom_doc->createElement("nome", $row['nome'] );
$data1 = $dom_doc->createElement("data1", $row['data'] );
$data2 = $dom_doc->createElement("data2", $row['data2'] );
$contact->appendChild($nome);
$contact->appendChild($data1);
$contact->appendChild($data2);
$element->appendChild($contact);
$dom_doc->appendChild($element);
What can I change to fix my problem, I am using utf-8???
Please try to put directly 'á', 'olá' or 'ção' in your script.
$data1 = $dom_doc->createElement("data1", 'ção');
If you don't have problem, this is probably the data you get from mysql that are wrongly encoded.
Are you sure your mysql outputs correct UTF-8?
To know that, make your PHP dump your data in an HTML document with meta tag set to UTF-8 and see if the characters display correctly.
You can also call :
$data1 = $dom_doc->createElement("data1", mb_detect_encoding($row['data']));
and see what encoding is detected by PHP for your data.
If you can't convert the data from your database, or change its settings, you can use mb_convert to do it on-the-fly : http://www.php.net/manual/en/function.mb-convert-encoding.php
You are using utf-8, the 8-bit unicode encoding format. Even though it properly supports all 1,112,064 code points in Unicode its possible that there is an issue here.
Try UTF-16 as the standard, just an idea. See below:
$dom_doc = new DOMDocument("1.0", "utf-16");
OR
$dom_doc = new DOMDocument("1.0", "ISO-10646");

Ampersands in database

I am trying to write a php function that goes to my database and pulls a list of URLS and arranges them into an xml structure and creates an xml file.
Problem is, Some of these urls will contain an ampersand that ARE HTML encoded. So, the database is good, but currently, when my function tries to grab these URLS, the script will stop at the ampersands and not finish.
One example link from database:
http://www.mysite.com/myfile.php?select=on&league_id=8&sport=15
function buildXML($con) {
//build xml file
$sql = "SELECT * FROM url_links";
$res = mysql_query($sql,$con);
$gameArray = array ();
while ($row = mysql_fetch_array($res))
{
array_push($row['form_link']);
}
$xml = '<?xml version="1.0" encoding="utf-8"?><channel>';
foreach ($gameArray as $link)
{
$xml .= "<item><link>".$link."</link></item>";
}
$xml .= '</channel>';
file_put_contents('../xml/full_rankings.xml',$xml);
}
mysql_close($con);
session_write_close();
If i need to alter the links in the database, that can be done.
You can use PHP's html_entity_decode() on the $link to convert & back to &.
In your XML, you could also wrap the link in <![CDATA[]]> to allow it to contain the characters.
$xml .= "<item><link><![CDATA[" . html_entity_decode($link) . "]]></link></item>";
UPDATE
Just noticed you're actually not putting anything into the $gameArray:
array_push($row['form_link']);
Try:
$gameArray[] = $row['form_link'];
* #Musa looks to have noticed it first, for due credit.
Look at this line
array_push($row['form_link']);
you never put anything in the $gameArray array, it should be
array_push($gameArray, $row['form_link']);
You need to use htmlspecialchars_decode. It will decode any encoded special characters in string passed to it.
This is most likely what you are looking for:
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Read the documentation, there are examples at the bottom of the page...
'&' in oracleSQL and MySQL are used in queries as a logical operator which is why it is tossing an error.
You may also want to decode the HTML...

Categories