473,835 Members | 1,829 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how do xml parsers detect bad characters?

2 years ago I asked, on this newsgroup, how to weed out non-UTF-8
characters from my RSS feed. I was told that I could not do so with
certainty, but I could try various tricks that would give me maybe
99%. I notice, however, that XML parsers seem to have 100% certainty
when they find bad characters. Consider the last error that I get from
this validation service:

http://validator.w3.org/feed/check.c...%2Frss2221.xml
What PHP code would give me this kind of 100% certainty? It seems to
me that, whatever the XML parsers do to determine a bad character, I
could also do, so as to make sure no such character makes it into my
feed.

Mar 19 '07 #1
2 3203
lawrence k wrote:
What PHP code would give me this kind of 100% certainty?
I was bored so wrote this. I'm quite proud of myself, as I wrote it and
ran it and it worked first time! :-)

It not only *checks* that the UTF-8 is valid, it *forces* it to be valid.

<?php

/**
* PHP UTF-8 Validation Library
* Copyright (C) 2007 Toby Inkster
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @author Toby Inkster <URL:http://tobyinkster.co. uk/>
* @copyright Copyright (C) 2007 Toby Inkster
* @license http://www.gnu.org/copyleft/lgpl.html GNU Lesser General Public Licence
*/

/**
* Utlity function to retrieve the first byte from a string.
*
* Note this function has a side-effect. As well as returning the
* first byte of the string, it also modifies the string passed
* as a parameter to remove the initial byte.
*
* @param string $string String to shift.
* @return string First byte of string.
*/
function shift_byte (&$string)
{
if (strlen($string )<1)
return FALSE;

$byte = substr($string, 0, 1);
$string = substr($string, 1);
return $byte;
}

/**
* Validate a string as UTF-8, and modify the string to remove nasties.
*
* Note this function has a side-effect. As well as returning a
* boolean to indicate whether the given string was valid, it also
* modifies the string replacing any invalid characters with a
* replacement character. (The replacement character is a question
* mark, but you can change this if you like.)
*
* Note that in UTF-8, most characters have several alternative
* representations . RFC 3629 says that the shortest representation
* is the correct one. Other representations ("overlong forms")
* are not valid. Earlier UTF-8 specifications did not prohibit
* overlong forms, though suggest emitting a warning when one is
* encountered. This function DOES NOT CHECK FOR OVERLONG FORMS!
*
* @param string $string String to validate.
* @return boolean Was the string valid or not?
*/
function validate_utf8 (&$string)
{
$new = '';
$valid = TRUE;
$replacement = '?';

/* Loop through each UTF-8 character. */
while (strlen($string ))
{
/* Array of bytes to store this character. */
$c = array();

/* Firstly, assume that a character is a single byte. */
$c[0] = shift_byte($str ing);

/* "Seven Z" notation. */
if (ord($c[0]) <= 0x7F)
{
$new .= $c[0];
}

/* "Five Y, Six Z" notation. */
elseif ((ord($c[0]) >= 0xC2) && (ord($c[0]) <= 0xDF))
{
$c[1] = shift_byte($str ing);

if ((ord($c[1]) >= 0x80) && (ord($c[1]) <= 0xBF))
{
$new .= $c[0].$c[1];
}
else
{
$new .= $replacement;
$valid = FALSE;
}
}

/* "Four X, Six Y, Six Z" notation. */
elseif ((ord($c[0]) >= 0xE0) && (ord($c[0]) <= 0xEF))
{
$c[1] = shift_byte($str ing);
$c[2] = shift_byte($str ing);

if ((ord($c[1]) >= 0x80) && (ord($c[1]) <= 0xBF)
&& (ord($c[2]) >= 0x80) && (ord($c[2]) <= 0xBF))
{
$new .= $c[0].$c[1].$c[2];
}
else
{
$new .= $replacement;
$valid = FALSE;
}
}

/* "Three W, Six X, Six Y, Six Z" notation. */
elseif ((ord($c[0]) >= 0xE0) && (ord($c[0]) <= 0xEF))
{
$c[1] = shift_byte($str ing);
$c[2] = shift_byte($str ing);
$c[3] = shift_byte($str ing);

if ((ord($c[1]) >= 0x80) && (ord($c[1]) <= 0xBF)
&& (ord($c[2]) >= 0x80) && (ord($c[2]) <= 0xBF)
&& (ord($c[3]) >= 0x80) && (ord($c[3]) <= 0xBF))
{
$new .= $c[0].$c[1].$c[2].$c[3];
}
else
{
$new .= $replacement;
$valid = FALSE;
}
}

else
{
$new .= $replacement;
$valid = FALSE;
}

}

$string = $new;
return $valid;
}

?>

--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
Mar 21 '07 #2
On Mar 21, 9:46 am, Toby A Inkster <usenet200...@t obyinkster.co.u k>
wrote:
lawrence k wrote:
What PHP code would give me this kind of 100% certainty?

I was bored so wrote this. I'm quite proud of myself, as I wrote it and
ran it and it worked first time! :-)

It not only *checks* that the UTF-8 is valid, it *forces* it to be valid.
That is brilliant, elegant code. Thank you.

Mar 23 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
6066
by: Will Stuyvesant | last post by:
There seems to be no XML parser that can do validation in the Python Standard Libraries. And I am stuck with Python 2.1.1. until my web master upgrades (I use Python for CGI). I know pyXML has validating parsers, but I can not compile things on the (unix) webserver. And even if I could, the compiler I have access to would be different than what was used to compile python for CGI. I need to write a CGI script that does XML validation...
0
1469
by: dagurp | last post by:
I have this code: import xml.parsers.expat parser = xml.parsers.expat.ParserCreate(encoding="UTF-8") text = unicode("<div>þórður</div>",'UTF-8') print parser.Parse(text,1) And this is what I get: UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-6: ordinal not in range(128)
1
5412
by: Roy | last post by:
Hi, I have a problem that I have been working with for a while. I need to be able from server side (asp.net) to detect that the file i'm streaming down to the client is saved completely/succsessfully on the client's computer before updating some metadata on the server (file downloaded date for instance) However, All examples i have tried, and all examples I have found that other people says works - doesn't work for me :-(
7
2100
by: Nikhil | last post by:
Hi, I was interested in knowing of there are parsers in C than can parse C code in some form of Data Structures and then after some user manuplation, write back the code in a file. A commercial tool which can do that would be the best ... Thanks,
2
3744
by: dwelch91 | last post by:
Hi, c.l.p.'ers- I am having a problem with the import of xml.parsers.expat that has gotten me completely stumped. I have two programs, one a PyQt program and one a command line (text) program that both eventually call the same code that imports xml.parsers.expat. Both give me different results... The code that gets called is (print statements have been added for debugging):
0
3195
by: JosAH | last post by:
Greetings, welcome back at the sequel of the parsers article chapter. This part is dedicated to the ExpressionParser, the largest parser class for our little language. This class parses a complete expression and just like the other parser classes calls the Generator on the fly. When the parse has completed successfully, the generated code is returned. Otherwise the parse is aborted and an exception is thrown telling the reason of the...
0
3383
by: JosAH | last post by:
Greetings, this week's article part discusses the parsers used for our little language. We will implement the parsers according to the grammar rules we defined in the second part of this article. As you will see shortly, the implementation of the parsers is an almost one-to-one translation of those grammar rules. Recursive descent parsing The grammar rules are highly recursive, i.e. one rule mentions another rule
7
2201
by: billsahiker | last post by:
if an xml file specifies an encoding, e.g., utf16, do xml browsers and xml editors read and verify each character in the file to make sure it is utf16? and throw an error if it is not, or. do they do an automatic filtering/converting to utf16, or do they do something else? Do they default to utf8 if the xml file does not specify an encoding? Bill
7
2659
by: Peter | last post by:
Hello I have an UTF string, how can i detect what language it is? thanks from Peter (cmk128@hotmail.com)
0
9803
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9652
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10560
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9344
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7766
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6963
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5804
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4433
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3993
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.