Я знаю, что это старая ветка (но ответьте на это, потому что также ищите решение этой проблемы). Я сделал простой способ заменить содержимое одной строкой при его использовании. Чтобы лучше понять метод, я также добавлю несколько контекстных именованных функций.
Теперь это часть моей библиотеки, поэтому здесь указаны все имена функций, все функции начинаются с префикса su.
Это очень простой в использовании и очень мощный (и довольно мало кода).
Вот код:
function suSetHtmlElementById( &$oDoc, &$s, $sId, $sHtml, $bAppend = false, $bInsert = false, $bAddToOuter = false )
{
if( suIsValidString( $s ) && suIsValidString( $sId ))
{
$bCreate = true;
if( is_object( $oDoc ))
{
if( !( $oDoc instanceof DOMDocument ))
{ return false; }
$bCreate = false;
}
if( $bCreate )
{ $oDoc = new DOMDocument(); }
libxml_use_internal_errors(true);
$oDoc->loadHTML($s);
libxml_use_internal_errors(false);
$oNode = $oDoc->getElementById( $sId );
if( is_object( $oNode ))
{
$bReplaceOuter = ( !$bAppend && !$bInsert );
$sId = uniqid('SHEBI-');
$aId = array( "<!-- $sId -->", "<!--$sId-->" );
if( $bReplaceOuter )
{
if( suIsValidString( $sHtml ) )
{
$oNode->parentNode->replaceChild( $oDoc->createComment( $sId ), $oNode );
$s = $oDoc->saveHtml();
$s = str_replace( $aId, $sHtml, $oDoc->saveHtml());
}
else { $oNode->parentNode->removeChild( $oNode );
$s = $oDoc->saveHtml();
}
return true;
}
$bReplaceInner = ( $bAppend && $bInsert );
$sThis = null;
if( !$bReplaceInner )
{
$sThis = $oDoc->saveHTML( $oNode );
$sThis = ($bInsert?$sHtml:'').($bAddToOuter?$sThis:(substr($sThis,strpos($sThis,'>')+1,-(strlen($oNode->nodeName)+3)))).($bAppend?$sHtml:'');
}
if( !$bReplaceInner && $bAddToOuter )
{
$oNode->parentNode->replaceChild( $oDoc->createComment( $sId ), $oNode );
$sId = &$aId;
}
else { $oNode->nodeValue = $sId; }
$s = str_replace( $sId, $bReplaceInner?$sHtml:$sThis, $oDoc->saveHtml());
return true;
}
}
return false;
}
// A function of my library used in the function above:
function suIsValidString( &$s, &$iLen = null, $minLen = null, $maxLen = null )
{
if( !is_string( $s ) || !isset( $s{0} ))
{ return false; }
if( $iLen !== null )
{ $iLen = strlen( $s ); }
return (( $minLen===null?true:($minLen > 0 && isset( $s{$minLen-1} ))) &&
$maxLen===null?true:($maxLen >= $minLen && !isset( $s{$maxLen})));
}
Некоторые функции контекста:
function suAppendHtmlById( &$s, $sId, $sHtml, &$oDoc = null )
{ return suSetHtmlElementById( $oDoc, $s, $sId, $sHtml, true, false ); }
function suInsertHtmlById( &$s, $sId, $sHtml, &$oDoc = null )
{ return suSetHtmlElementById( $oDoc, $s, $sId, $sHtml, false, true ); }
function suAddHtmlBeforeById( &$s, $sId, $sHtml, &$oDoc = null )
{ return suSetHtmlElementById( $oDoc, $s, $sId, $sHtml, false, true, true ); }
function suAddHtmlAfterById( &$s, $sId, $sHtml, &$oDoc = null )
{ return suSetHtmlElementById( $oDoc, $s, $sId, $sHtml, true, false, true ); }
function suSetHtmlById( &$s, $sId, $sHtml, &$oDoc = null )
{ return suSetHtmlElementById( $oDoc, $s, $sId, $sHtml, true, true ); }
function suReplaceHtmlElementById( &$s, $sId, $sHtml, &$oDoc = null )
{ return suSetHtmlElementById( $oDoc, $s, $sId, $sHtml, false, false ); }
function suRemoveHtmlElementById( &$s, $sId, &$oDoc = null )
{ return suSetHtmlElementById( $oDoc, $s, $sId, null, false, false ); }
Как это использовать:
В следующих примерах я предполагаю, что в переменную с именем $sMyHtml
уже загружено содержимое, а переменная $sMyNewContent
содержит новый html. Переменная $sMyHtml
содержит элемент с именем / с идентификатором 'example_id
'.
// Example 1: Append new content to the innerHTML of an element (bottom of element):
if( suAppendHtmlById( $sMyHtml, 'example_id', $sMyNewContent ))
{ echo $sMyHtml; }
else { echo 'Element not found?'; }
// Example 2: Insert new content to the innerHTML of an element (top of element):
suInsertHtmlById( $sMyHtml, 'example_id', $sMyNewContent );
// Example 3: Add new content ABOVE element:
suAddHtmlBeforeById( $sMyHtml, 'example_id', $sMyNewContent );
// Example 3: Add new content BELOW/NEXT TO element:
suAddHtmlAfterById( $sMyHtml, 'example_id', $sMyNewContent );
// Example 4: SET new innerHTML content of element:
suSetHtmlById( $sMyHtml, 'example_id', $sMyNewContent );
// Example 5: Replace entire element with new content:
suReplaceHtmlElementById( $sMyHtml, 'example_id', $sMyNewContent );
// Example 6: Remove entire element:
suSetHtmlElementById( $sMyHtml, 'example_id' );