问题
I would like to replace the € sign in $XML_COMMENT with "euros" before adding to a xml file.
The € sign not being a utf-8 character I get and error message from simplexml
Warning: SimpleXMLElement::addAttribute(): string is not in UTF-8 in ...
Warning: SimpleXMLElement::asXML(): output conversion failed due to conv error, bytes 0x82 0x26 0x61 0x6D in ....
The euro sign appears in the MySQL (utf-8) database as '€'
But appears correctly in the textarea on the webpage.
I tried to use these different str_replace
$XML_COMMENT=str_replace('€','euros',$XML_COMMENT)
$XML_COMMENT=str_replace('€','euros',$XML_COMMENT)
$XML_COMMENT=str_replace(chr(128),'euros',$XML_COMMENT)
$XML_COMMENT=str_replace(chr(0xE2).chr(0×82).chr(0xAC),'euros',$XML_COMMENT)
$XML_COMMENT=str_replace(chr(0x82).chr(0x26).chr(0x61).chr(0x6D),'euros',$XML_COMMENT)
without success
FYI: I'm using utf-8 everywhere (MySQL, Web Page and XML)
Here's my code
// ? : $XML_COMMENT= "bla bla bla € bla bla bla";
// ? : $XML_COMMENT= "bla bla bla € bla bla bla";
// expected : $XML_COMMENT= "bla bla bla euros bla bla bla";
$ProductLog_XML = simplexml_load_file($file);
$ProductUpdate = $ProductLog_XML->order->product->addChild('update');
$ProductUpdate->addAttribute('comment',$XML_COMMENT);
$fp=fopen(file, "w");
fwrite($fp, $ProductLog_XML->asXML());
fclose($fp);
Is there any alternative using regex / preg_replace ?
回答1:
You can try htmlentities()
to convert all entities including the euro sign, so they appear like €
.
I would use it in the following manner: htmlentities($str, ENT_QUOTES|"ENT_HTML401", "UTF-8", true)
You may choose to use: htmlentities($XML_COMMENT, ENT_QUOTES | ENT_IGNORE, "UTF-8", true)
. For a full explanation of what the flags change, visit the link below.
As requested by OP @baptme (see comments).
Source: php.net reference
回答2:
I had the same problem and the following works for me where the original HTML page is in UTF-8 and using &euro which after cURL-ing with PHP spits out as "€"
$nodeValue = str_replace(chr(0xE2).chr(0x82).chr(0xAC), "", $nodeValue)
来源:https://stackoverflow.com/questions/10948176/php-preg-replace-%e2%82%ac-sign-with-euro