2013-07-12 77 views
3

編輯:該字符串被輸出和由瀏覽器解釋。愚蠢的錯誤。PHP長度的空字符串32

在我的項目,我創建了一個類來生成我需要的HTML標籤,而回聲大家都出去了我自己。我在名爲Card的php類中有一個名爲generateTag($control, $isCardValue = true)的函數。該函數根據通過數組參數$control傳遞的屬性生成HTML標記。下面是函數的樣子:

public function generateTag($control, $isCardValue = true) { 
    if ($isCardValue) { 
     // First we convert the 'class' element to an array 
     if (isset($control['class']) && gettype($control['class']) !== 'array') { 
      $control['class'] = array($control['class']); 
     } 
     // Then we add the 'card-value' class to that array. 
     $control['class'][] = 'card-value'; 
    } 

    // The tag key is mandatory 
    $tag = '<' . $control['tag']; 
    // All keys other than 'tag' & 'content' are considered attributes for the HTML tag. 
    foreach ($control as $key => $value) { 
     switch ($key) { 
      case 'tag': 
       break; 

      case 'content': 
       break; 

      default: 
       if (gettype($value) === 'array') { 
        $tag .= ' ' . $key . '="' . implode(' ', $value) . '"'; 
       } elseif (gettype($value) === 'NULL') { 
        $tag .= ' ' . $key; 
       } else { 
        $tag .= ' ' . $key . '="' . $value . '"'; 
       } 
       break; 
     } 
    } 
    $tag .= '>'; 

    // If the 'content' key is not passed through $control, we assume that the tag 
    // doesn't need to be closed (e.g. <input> doesn't need a closing tag) 
    if (isset($control['content'])) { 
     if (gettype($control['content']) === 'array') { 
      foreach ($control['content'] as $child) { 
       $tag .= $this->generateTag($child); 
      } 
     } else { 
      $tag .= $control['content']; 
     } 
     $tag .= '</' . $control['tag'] . '>'; 
    } 

    return $tag; 
} 

我用這個功能來創建所有的<select><option>標籤。我只是遍歷數組生成標籤:

foreach ($lists['tags'] as $key => $tag) { 
    $tag_options[$key] = array(
     'tag' => 'option', 
     'value' => $tag['tag_id'], 
     'content' => $tag['tag_name_en'], 
    ); 
    var_dump($card->generateTag($tag_options[$key], false)); 
} 

這就是事情變得怪異。我呼籲生成的字符串的var_dump,我得到下面的輸出:

string(32) "" string(35) "" string(33) "" string(33) "" string(38) "" string(32) "" string(42) "" string(30) "" string(41) "" string(34) "" string(35) "" string(34) "" string(29) "" string(36) "" string(37) "" string(31) "" string(36) "" string(67) "" string(36) "" string(33) "" string(36) "" string(36) "" 

看來,它是創造長度的空字符串〜35?最奇怪的是,當我叫substr($tag_options[$key], 0, 1),它給了我<因爲它應該。但是當我打電話給substr($tag_options[$key], 0, 2)時,它給了我長度爲2的「空」字符串。對發生了什麼事情有所瞭解?

+0

你輸出爲HTML到瀏覽器? 'var_dump'不是HTML編碼。 – Ryan

+0

'

+0

這裏張貼的代碼太多了。我會建議將問題減少到顯示問題的一些線上 - 而不是其他問題。大多數情況下,當你這樣做時,你也會解決你的原始問題 – hek2mgl

回答

4

既然你正在查看在瀏覽器中輸出,它仍然在解析每個字符串作爲HTML代碼的HTML,你沒有看到它呈現的頁面上。 var_dump不會執行HTML編碼。

當你發現,它工作在你的頁面的源代碼。 :)