2011-02-10 7 views
0

私はPHPのDOMDocument->getElementById->nodeValueを使って特定のDOM要素のHTMLを設定しています。問題は、文字列をHTMLエンティティに変換されていることである: 例: nodeValue = html_entity_decode('<b>test</b>');は出力「試験」すべきではなく、それは出力「&lt;b&gt;test&lt;/b&gt;php DOMDocument-> getElementById-> nodeValue sripping html

任意のアイデアはなぜですか?私はここがhtml_entity_decode機能

を使用していない場合でも、これが起こるかは今働いている私の更新されたスクリプト...です:

// Construct a DOM object for updating the affected node 
$html = new DOMDocument("1.0", "utf-8"); 
if (!$html) return FALSE; 

// Load the HTML file in question 
$loaded = $html->loadHTMLFile($data['page_path']); 
if (!$loaded) 
{ 
    print 'Failed to load file'; 
    return FALSE; 
} 

// Establish the node being updated within the file 
foreach ($data['divids'] as $divid) 
{ 
    $element = $html->getElementById($divid); 
    if (is_null($element)) 
    { 
     print 'Failed to get existing element'; 
     return FALSE; 
    } 

    $newelement = $html->createElement('div'); 
    if (is_null($newelement)) 
    { 
     print 'Failed to create new element'; 
     return FALSE; 
    } 
    $newelement->setAttribute('id', $divid); 
    $newelement->setAttribute('class', 'reusable-block'); 

    // Perform the replacement 
    $newelement->nodeValue = $replacement; 
    $parent = $element->parentNode; 
    $parent->replaceChild($newelement, $element); 

    // Save the file back to its location 
    $saved = $html->saveHTMLFile($data['page_path']); 
    if (!$saved) 
    { 
     print 'Failed to save file'; 
     return FALSE; 
    } 
} 

// Replace HTML entities left over 
$content = files::readFile($data['page_path']); 
$content = str_replace('&lt;', '<', $content); 
$content = str_replace('&gt;', '>', $content); 
if ([email protected]($handle, $content)) 
{ 
    print 'Failed to replace entities'; 
    return FALSE; 
} 

答えて

2

これは正しい動作です - あなたのタグは、文字列に変換されていますXMLの文字列に山括弧を含めることはできません(タグのみ)。 DOMNodeをにHTMLに変換し、代わりにそれを追加してみてください。作業例と

$node = $mydoc->createElement("b"); 
$node->nodeValue = "test"; 
$mydoc->getElementById("whatever")->appendChild($node); 

アップデート:

$html = '<html> 
    <body id="myBody"> 
     <b id="myBTag">my old element</b> 
    </body> 
</html>'; 

$mydoc = new DOMDocument("1.0", "utf-8"); 
$mydoc->loadXML($html); 

// need to do this to get getElementById() to work 
$all_tags = $mydoc->documentElement->getElementsByTagName("*"); 
foreach ($all_tags as $element) { 
    $element->setIdAttribute("id", true); 
} 

$current_b_tag = $mydoc->getElementById("myBTag"); 
$new_b_tag = $mydoc->createElement("b"); 
$new_b_tag->nodeValue = "my new element"; 
$result = $mydoc->getElementById("myBody"); 
$result->replaceChild($new_b_tag, $current_b_tag); 

echo $mydoc->saveXML($mydoc->documentElement); 
+0

問題は、私は...それを付加していない要素を交換してるということです。悲しいことに、 –

+0

次にremoveChild()とreplaceChild()メソッドが興味深いかもしれません:http://php.net/manual/en/class.domnode.php – alexantd

+0

このようにすると、HTMLをエンティティに変換します... oddly –