Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

php - DOMDocument and windows-1250 encoding

So, I'm writing the code that is supposed to parse different websites, and some of them use windows-1250 encoding, and some of them use 'utf-8'. I don't have any impact over those websites, and you can probably guess that those pages with 'windows-1250' are giving me headache. So, here's the code that I'm using:

    $doc = new DOMDocument();
        @$doc->loadHTML($response);

        $xpath = new DOMXpath($doc);
        $anchors = $xpath->query("//a[@href]");
        foreach( $anchors as $anchor) {
            $href = $anchor->getAttribute("href");
            $anchor->setAttribute("href", 'http://example.com/');
        }

        $response = $xpath->document->saveHTML();

and here's the output in browser when I try to run this script:

Warning: DOMDocument::saveHTML(): output conversion failed due to conv error, bytes 0x9A 0x61 0x72 0x6B

So, is there a way to handle this error with 'windows-1250' encoding, that will work work utf-8 also ? I tried using utf_encode with $response and that passes, but then international characters are messed up.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you are just trying to change the href of all of your anchor tags then you could just use jquery

The code would look like this:

  //loop through the anchor tags
 $("a").each(function(){//begin each function

  //set the href attributes
  $(this).attr("href","http://example.com/");


  });//end each function

Here is a jsfiddle example: http://jsfiddle.net/fu5fxawm/1/

If you hover over the links you will see that they have been changed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...