开发者

removing quotes in PHP a bit complicated maybe

I have this peace of code which brings string searches for img tags in it and adds class to img tags. Then I save everything back and send it to database.

$doc = new DOMDocument();
$doc->loadHTML($article_header);

$imgs = $doc->getElementsBy开发者_开发技巧TagName('img');
foreach ($imgs as $img) {

    if($img->getAttribute('class')){
    } 
    else {
        $img->setAttribute('class', 'someclass');
        $article_header = $doc->saveXml();
    }
}

Problem is that the result becomes like this

<?xml version="1.0" standalone="yes"?> <!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body><p><img
src="&quot;some_url/some_pic.jpg&quot;"
alt="&quot;&quot;" width="&quot;528&quot;"
height="&quot;722.0512820512821&quot;"
class="someclass"/></p></body></html>

So how can I get rid of this quot; things ??? I've read that it's phps magic quotes and tryied stripslashes on them like this

$article_header = stripslashes($doc->saveXml());

But this doesn't help.

UPDATE

<img width="\"528\"" height="\"722.0512820512821\"" alt="\"\"" src="%5C%22sources/public/users/103/articles/2011-06-11/3/img/1170x1600.gif%5C%22">

This kind of weird code I get from TinyMCE editor. Before I do DOM things to it. As I see it's already damaged. I wonder how :(

UPDATE 2

Problem found This was because of this

$article_header=mysql_real_escape_string($_POST['article_header']);

If I remove mysql_real_escape_string everything is ok. But New question if I do so, what should I use instead of it to add some security to my script?

SOLVED I removed mysql_real_escape_string and use them only when I'm passing data to mysql


I don't understand reason of this problem but you can use htmlspecialchars_decode(); to convert &quot; to "


you code should be:

$doc = new DOMDocument();
$doc->loadHTML($article_header);

$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img) {

    if(!$img->getAttribute('class')){
        $img->setAttribute('class', 'someclass');
    }
}
$article_header = $doc->saveXml();

update: for the next question, is enough that you are using DomDocument as he's parsing all the data and will give error if something is wrong.

when you want to save it to mysql you add mysql_real_escape_string() for security ..


Well, these &quot; is a " character, so you can't stripslashes these characters as they are not " itself, just representation of them. You can do str_replace("&quot;", '"', $string);, but that's not the best answer, as you should escape " before inserting to db, then you'll get needed result.


SOLVED I removed mysql_real_escape_string and use them only when I'm passing data to mysql

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜