问题描述
如何删除打开和关闭XML之间的特殊字符?
我尝试使用递归函数。因此在这种情况下,它对我不起作用。
$sampleXML = '<?xml version="1.0" encoding="ISO-8859-1"?>
<mainTag type="user">
<note>
<PersonName>
<GivenName>Replace & this</GivenName>
<MiddleName>Replace < this</MiddleName>
</PersonName>
<Aliases>
<PersonName>
<GivenName>Replace > this</GivenName>
<FamilyName>Replace " this</FamilyName>
</PersonName>
</Aliases>
<DemographicDetail>
<GovernmentId countryCode="US">testIDs data </GovernmentId>
<DateOfBirth>2000-12-12</DateOfBirth>
</DemographicDetail>
</note>
<anothertag>
<data type="credit">
<Vendor score="yes"> vendor name </Vendor>
</data>
</anothertag>
</mainTag>';
$doc = new DOMDocument;
$doc->loadXML($xml);
$this->removeSpecialCharacterNodes($doc);
$xpath = new DOMXpath($doc);
$xml = $doc->saveXML($doc,LIBXML_NOEMPTYTAG);
替换以下内容
& by &
> by <
< by >
" by "
' by '
我使用了以下递归代码,但返回空值
public function removeSpecialCharacterNodes(DOMNode $node) {
// echo "aa";
// var_dump($node->childNodes);
$str = $node->childNodes;
var_dump($node->childNodes);
foreach ($node->childNodes as $child){
if($child->hasChildNodes()) {
$this->removeSpecialCharacterNodes($child);
} else{
$child->nodeValue = str_ireplace('&','&',$child->nodeValue);
}
}
}
更新: 我已使用字符串replace和htmlspecialchars仍然是特殊字符的方式进行了更新。
$doc = new DOMDocument;
$doc->loadXML( $sampleXML);
foreach ($doc->documentElement->childNodes as $node) {
if($node->nodeType==1){
$oldAddressLine = $node->getElementsByTagName('AddressLine')->Item(0);
// $elle = str_ireplace(
// array( "'"),// array( "'"),// $oldAddressLine->nodeValue
// );
// $newelement = $doc->createElement('AddressLine',$elle);
$chk = $oldAddressLine->nodeValue;
$newelement = $doc->createElement('AddressLine',htmlspecialchars( $chk,ENT_XML1 ));
if ($oldAddressLine->parentNode != null) {
$oldAddressLine->parentNode->replaceChild($newelement,$oldAddressLine);
}
}
}
$xpath = new DOMXpath($doc);
$finalVal = $doc->saveXML($doc,LIBXML_NOEMPTYTAG);
echo "<pre>".htmlentities($finalVal)."</pre>"; exit;
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)