将div的innerhtml连接成字符串变量

时间:2013-01-15 20:01:31

标签: php

我试图将div的innerhtml连接成字符串变量:
游戏变量:

$games = '';


DOMinnerHTML函数:

function DOMinnerHTML($element) 
{ 
    $innerHTML = ""; 
    $children = $element->childNodes; 
    foreach ($children as $child) 
    { 
        $tmp_dom = new DOMDocument(); 
        $tmp_dom->appendChild($tmp_dom->importNode($child, true)); 
        $innerHTML.=trim($tmp_dom->saveHTML()); 
    } 
    return $innerHTML; 
} 


ExtractFromType函数:

function ExtractFromType($type)
{
$html = file_get_contents('www.site.com/' .$type);
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
if (strpos($div->getAttribute('style'),'MyString') !== false) {

//////
$games = $games.DOMinnerHTML($div);
//////

}
}
}


码:

ExtractFromType('MyType');
echo $games; // = Nothing.

此代码不返回任何内容。

1 个答案:

答案 0 :(得分:0)

$games在全局范围内定义,并且在ExctractFromType内不可用。在函数内定义它,然后返回值:

function ExtractFromType($type) {
  $html = file_get_contents('www.site.com/' .$type);
  $dom = new domDocument;
  @$dom->loadHTML($html);
  $dom->preserveWhiteSpace = false;
  $divs = $dom->getElementsByTagName('div');

  $games = '';
  foreach ($divs as $div) {
    if (strpos($div->getAttribute('style'),'MyString') !== false) {
      $games = $games.DOMinnerHTML($div);
    }
  }
}

echo ExtractFromType('MyType');