将nodevalue转换为字符串

时间:2012-01-06 07:52:36

标签: php html dom

使用dom html。我想将节点值转换为字符串:

 $html = @$dom->loadHTMLFile('url');


  $dom->preserveWhiteSpace = false;


  $tables = $dom->getElementsByTagName('body');


  $rows = $tables->item(0)->getElementsByTagName('tr');

  // loop over the table rows
  foreach ($rows as $text =>$row)
  {
$t=1;

   // get each column by tag name
      $cols = $row->getElementsByTagName('td');
//getting values

$rr = @$cols->item(0)->nodeValue;

print $rr; ( it prints values of all 'td' tag fine)
}
print $rr; ( it prints nothing) I want it to print here 

?>

我希望将nodevalues转换为字符串以进行进一步操作。

4 个答案:

答案 0 :(得分:1)

每次循环遍历foreach时,都会覆盖$rr变量的值。第二个print $rr将打印最后一个td的值 - 如果它为空,则它将不会打印任何内容。

如果你要做的是打印所有值,而是将它们写入数组:

$rr = array();
foreach($rows as $text =>$row) {
  $rr[] = $cols->item(0)->nodeValue;
}
print_r($rr);

答案 1 :(得分:1)

  // new dom object
  $dom = new DOMDocument();

  //load the html
  $html = @$dom->loadHTMLFile('http://webapp-da1-01.corp.adobe.com:8300/cfusion/bootstrap/');

  //discard white space
  $dom->preserveWhiteSpace = false;

  //the table by its tag name
  $tables = $dom->getElementsByTagName('head');

//get all rows from the table
  $la=array();
$rows = $tables->item(0)->getElementsByTagName('tr');

  // loop over the table rows
$array = array();
  foreach ($rows as $text =>$row)
  {
$t=1;
$tt=$text;
   // get each column by tag name
 $cols = $row->getElementsByTagName('td');
   // echo the values
      #echo @$cols->item(0)->nodeValue.'';
//      echo @$cols->item(1)->nodeValue.'';
$array[$row] = @$cols->item($t)->nodeValue;
}
print_r ($array);

它打印数组 ( ) 而已。我还使用了“$ cols-> item(0) - > nodeValue;”

答案 2 :(得分:0)

使用DOM::saveXMLDOM::saveHTML将节点值转换为字符串。

答案 3 :(得分:0)

你试过@ $ cols-> item(0) - > textContent