2

我正在尝试从远程位置加载 XML 源,因此我无法控制格式。不幸的是,我尝试加载的 XML 文件没有编码:

<ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql"> <NODE> </NODE> </ROOT>

当尝试类似的事情时:

$doc = new DOMDocument( );
$doc->load(URI);

我得到:

Input is not proper UTF-8, indicate encoding ! Bytes: 0xA3 0x38 0x2C 0x38

我已经想办法抑制这种情况,但没有运气。我应该如何加载它以便可以将它与 DOMDocument 一起使用?

4

4 回答 4

2

您必须将文档转换为 UTF-8,最简单的方法是使用utf8_encode()

DOM文档示例:

$doc = new DOMDocument();
$content = utf8_encode(file_get_contents($url));
$doc->loadXML($content);

简单 XML 示例:

$xmlInput = simplexml_load_string(utf8_encode(file_get_contents($url_or_file)));

如果您不知道当前编码,请使用mb_detect_encoding(),例如:

$content = utf8_encode(file_get_contents($url_or_file));
$encoding = mb_detect_encoding($content);
$doc = new DOMdocument();
$res = $doc->loadXML("<?xml encoding='$encoding'>" . $content);

笔记:

  • 如果无法检测到编码(函数将返回 FALSE),您可以尝试通过utf8_encode()强制编码。
  • 如果您通过加载 html 代码$doc->loadHTML,您仍然可以使用 XML 标头。

如果您知道编码,请使用iconv()进行转换:

$xml = iconv('ISO-8859-1' ,'UTF-8', $xmlInput)
于 2015-03-19T22:59:18.643 回答
1

您可以编辑文档(“对其进行预处理”)以指定它在添加 XML 声明时传递的编码。那是什么,当然,您必须确定自己。然后 DOM 对象应该解析它。

示例 XML 声明:

<?xml version="1.0" encoding="UTF-8" ?>
于 2009-08-30T16:48:42.280 回答
0

您可以尝试改用XMLReader类。XMLReader 是专门为 XML 设计的,并且可以选择使用何种编码(包括“null”表示无)。

于 2009-08-30T16:47:14.763 回答
-1

我遇到了类似的情况。我得到了一个应该是 UTF-8 编码的 XML 文件,但它包含一些错误的 ISO 字符。

我编写了以下代码将坏字符编码为 UTF-8

<?php

# The XML file with bad characters
$filename = "sample_xml_file.xml";

# Read file contents to a variable
$contents = file_get_contents($filename);

# Find the bad characters
preg_match_all('/[^(\x20-\x7F)]*/', $contents, $badchars);

# Process bad characters if some were found
if(isset($badchars[0]))
{
        # Narrow down the results to uniques only
        $badchars[0] = array_unique($badchars[0]);

        # Replace the bad characters with their UTF8 equivalents
        foreach($badchars[0] as $badchar)
        {
                $contents = preg_replace("/".$badchar."/", utf8_encode($badchar), $contents);
        }
}

# Write the fixed contents back to the file
file_put_contents($filename, $contents);

# Cleanup
unset($contents);

# Now the bad characters have been encoded to UTF8
# It will now load file with DOMDocument
$dom = new DOMDocument();
$dom->load($filename);

?>

我在以下位置更详细地发布了解决方案:http: //dev.strategystar.net/2012/01/convert-bad-characters-to-utf-8-in-an-xml-file-with-php/

于 2012-01-12T20:37:17.700 回答