如何逃避'&'在XML元素内的URL中

时间:2018-01-17 19:47:57

标签: javascript php xml escaping

如何在XML元素内的URL中转义&

我在JavaScript对象中有一个URL,我将对象传递给PHP,其中以下代码将其转换为XML,然后我将其放在XML文件中:

function array2xml($array, $xml = false){
    if($xml === false){
        $xml = new SimpleXMLElement('<items id="datasource"/>');
    }
    foreach($array as $key => $value){
        if(is_array($value)){
            array2xml($value, $newChild = $xml->addChild('item'));
            $newChild->addAttribute('id', $key);
        }
        else {
            $newChild = $xml->addChild('item', $value);
            $newChild->addAttribute('id', $key);
        }
    }
    return $xml->asXML();
}

网址需要2个查询参数,因此我需要&,但出于某种原因,我无法逃脱它而不允许我打开链接。

我尝试将&替换为&amp;&#38;%26<![CDATA[&]]>,但这些都不起作用。

1 个答案:

答案 0 :(得分:1)

class SimpleXMLExtended extends SimpleXMLElement {
  public function addCData($cdata_text) {
    $node = dom_import_simplexml($this); 
    $no   = $node->ownerDocument; 
    $node->appendChild($no->createCDATASection($cdata_text)); 
  } 
}

$xml = new SimpleXMLExtended('<items id="datasource"/>');
$newChild = $xml->addChild('item');
$newChild->addCData('t&st');
$newChild->addAttribute('id', 'key');
var_dump($xml->asXml());

因此,在您的情况下,我相信您只需将代码替换为:

class SimpleXMLExtended extends SimpleXMLElement {
  public function addCData($cdata_text) {
    $node = dom_import_simplexml($this); 
    $no   = $node->ownerDocument; 
    $node->appendChild($no->createCDATASection($cdata_text)); 
  } 
}

function array2xml($array, $xml = false){
    if($xml === false){
        $xml = new SimpleXMLExtended('<items id="datasource"/>');
    }
    foreach($array as $key => $value){
        if(is_array($value)){
            array2xml($value, $newChild = $xml->addChild('item'));
            $newChild->addAttribute('id', $key);
        }
        else {
            $newChild = $xml->addChild('item');
            $newChild->addCData($value);
            $newChild->addAttribute('id', $key);
        }
    }
    return $xml->asXML();
}

从这里得到答案:

How to write CDATA using SimpleXmlElement?