2011-02-10 3 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

어떤 아이디어 왜 출력? , 태그가 문자열로 변환되는 -이 적절한 행동이

// 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

: 내가의 html_entity_decode 기능 여기

를 사용하지 않는 경우에도이 지금 내 업데이트 스크립트 ... 노력하는 일이 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이 엔터티로 변환됩니다. 이상하게 –