2016-03-08 72 views
1

何時應該在HTML鏈接中使用&符號實體(&)?何時應該在HTML鏈接中使用&符號實體(&)?

上下文:我問的原因是我使用DOMDocument()<img>標籤轉換爲不同的HTML,並且該&符號被重複。對於我的具體示例,我認爲這是由於mb_convert_encoding(),但如果我不使用它,我還有其他問題。也許有其他時候不應該在HTML鏈接中使用&符號實體?

public static function substituteImg($template, $values, $classI='autoInsert', $classF='',$escape=false) { 
    $classesToReplace = array($classI); 
    if($template) { 
     $doc = new DOMDocument(); 
     $template = mb_convert_encoding($template, 'HTML-ENTITIES', 'UTF-8'); 
     $doc->loadHTML($template); 

     $xpath = new DOMXPath($doc); 
     foreach($xpath->query('//img') as $img) { 
      // get the classes into an array 
      $classes = explode(' ', $img->getAttribute('class')); // this will contain the classes assigned to the element 
      if (array_intersect($classes, $classesToReplace)) 
      { 

       // preprocess the image name to match the $values keys 
       $imageName = pathinfo($img->getAttribute("src"),PATHINFO_FILENAME); 
       if (isset($values[$imageName])) { 
        if(is_array($values[$imageName])){ 
         //Not a text node 
         switch($values[$imageName]['type']) 
         { 
          case 'a': 
           $element = $doc->createElement('a',htmlentities($values[$imageName]['value'])); 
           $element_href = $doc->createAttribute('href'); 
           $element_href->value=htmlentities($values[$imageName]['attr']); 
           $element->appendChild($element_href); 
           if($classF) { 
            $element_class = $doc->createAttribute('class'); 
            $element_class->value=$classF; 
            $element->appendChild($element_class); 
           } 
           break; 
          default:{trigger_error("Invalid element type", E_USER_ERROR);} 
         } 
        } 
        else {$element = $doc->createTextNode($escape?htmlentities($values[$imageName]):$values[$imageName]);} 
        $img->parentNode->replaceChild($element,$img); 
       } 
      } 
     } 
     $body = $doc->getElementsByTagName('body')->item(0); 
     $template=$doc->saveHTML($body); //Select the body tag 
     $template = str_replace(array('<body>', '</body>'), '', $template); //strip the body tags 
     unset($doc,$xpath); 
    } 
    return $template; 
} 

樣品陣列傳遞給substituteImg()

Array 
(
    [bla] => 2721930660 
    [link1] => Array 
     (
      [type] => a 
      [value] => Yes 
      [attr] => javascript:void(0) 
     ) 
    [link2] => Array 
     (
      [type] => a 
      [value] => link 
      [attr] => https://example.com/index.php?foo=123&amp;bar=321 
     ) 
) 

回答

2

,每當你想表達HTML,數據&其中內容是當你使用它的元素中,除了你應該使用&amp;明確標記爲CDATA(意思是<script><style>元素)。

您不應該使用使用&amp;當您使用DOM API來操作DOM中的文本時。 (這是你在這裏做的)。

如果DOM是從HTML文檔生成的,則在生成DOM時,&amp;將被解析爲&

如果您從DOM生成HTML,則在將其轉換爲HTML時,&將表示爲&amp;


對於我的具體的例子,我認爲這是發生由於mb_convert_encoding(),

不,這是由於$doc->saveHTML($body);將DOM轉換成HTML。

+0

謝謝。非常好的答案。因此,兩次不應該使用'&amp ;'在CDATA內部以及使用DOM API時。你能想到其他任何時候嗎? – user1032531

+0

基本上任何時候你正在處理一些不期望你編寫原始HTML源代碼的東西。 – Quentin

相關問題