0

我有这个代码:

        $strhtml = file_get_contents('05001400300320100033100.html');
        // create the DOMDocument object, and load HTML from a string
        $dochtml = new DOMDocument();
        $dochtml->loadHTML($strhtml);
        $elm = $dochtml->getElementById('upPanelActuciones');
        $segatiel= $dochtml->saveXml($elm);


        $order   = array("á","é","í","ó","ú","ñ");                      
        $replace = array("&aacute","&eacute","&iacute","&oacute","&uacute","&ntilde");
        $megin = str_replace($order, $replace,$segatiel); 

        echo $megin;

但显然 str_replace 函数不起作用,因为输出保留了稀有字符(如 ó)。有没有办法让 str_replace 工作?

在此先感谢您的帮助。

pd:我设置了 html charset Utf-8。

4

1 回答 1

1

更新

试试这个

$strhtml = file_get_contents('05001400300320100033100.html');
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById('upPanelActuciones');
$segatiel= $dochtml->saveXml($elm);
$trans = get_html_translation_table(HTML_ENTITIES);
unset($trans["\""], $trans["<"], $trans[">"]);
$megin = strtr($segatiel, $trans);
echo $megin;

str_replace 不适用于国际字符。

<?php
/**
 * Replace all occurrences of the search string with the replacement string.
 *
 * @author Sean Murphy <sean@iamseanmurphy.com>
 * @copyright Copyright 2012 Sean Murphy. All rights reserved.
 * @license http://creativecommons.org/publicdomain/zero/1.0/
 * @link http://php.net/manual/function.str-replace.php
 *
 * @param mixed $search
 * @param mixed $replace
 * @param mixed $subject
 * @param int $count
 * @return mixed
 */
if (!function_exists('mb_str_replace')) {
    function mb_str_replace($search, $replace, $subject, &$count = 0) {
        if (!is_array($subject)) {
            // Normalize $search and $replace so they are both arrays of the same length
            $searches = is_array($search) ? array_values($search) : array($search);
            $replacements = is_array($replace) ? array_values($replace) : array($replace);
            $replacements = array_pad($replacements, count($searches), '');

            foreach ($searches as $key => $search) {
                $parts = mb_split(preg_quote($search), $subject);
                $count += count($parts) - 1;
                $subject = implode($replacements[$key], $parts);
            }
        } else {
            // Call mb_str_replace for each subject in array, recursively
            foreach ($subject as $key => $value) {
                $subject[$key] = mb_str_replace($search, $replace, $value, $count);
            }
        }

        return $subject;
    }
}
?>

但是您正在寻找的不是 htmlentities() 吗? http://www.php.net/manual/en/function.htmlentities.php

于 2013-02-09T01:41:18.387 回答