在 React Native 方法中,我获取了一个以 ISO-8859-1 编码的 xml。
只要提取完成,我就会尝试将其转换为 UTF-8。
这里的代码:
const iconv = require('iconv-lite');
fetch('http://www.band.uol.com.br/rss/colunista_64.xml', {
headers: {
"Content-type": "text/xml; charset=ISO-8859-1"
}
})
.then(res=>res.text()})
.then(text => {
const decodedText = iconv.decode(Buffer.from(text, 'latin1'), 'latin1')
, output = iconv.encode(decodedText, 'utf8')
console.log(output.toString())
})
问题是: body 的所有特殊字符都被替换为“¿½”
对于转换,我使用的是包
iconv-lite
这个问题的更好解决方法是什么?
最佳答案
最好的解决方法是使用 res.arrayBuffer()
相反 res.text()
, 只要 Buffer 构造函数接受 ArrayBuffer
编码:
fetch('http://www.band.uol.com.br/rss/colunista_64.xml')
.then(res => res.arrayBuffer())
.then(arrayBuffer => iconv.decode(new Buffer(arrayBuffer), 'iso-8859-1').toString())
.then(converted => console.log(converted))
关于xml - 提取响应的编码转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41412253/