【问题标题】:convert a nodevalue into a string将节点值转换为字符串
【发布时间】:2012-01-10 18:11:57
【问题描述】:

在 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 

?>

我希望将节点值转换为字符串以便进一步操作。

【问题讨论】:

  • 欢迎来到 SO。请花点时间让您的问题更易读,以便我们更好地帮助您。
  • 您正在使用 @ 运算符抑制错误。如果发生错误,您将不会注意到它。例如。如果无法加载文档(服务器关闭),则没有节点可以提取任何内容。此外,如果你正确缩进你的代码,它会更好地阅读和更容易处理。

标签: php html dom


【解决方案1】:

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

如果您尝试打印所有值,请将它们写入数组:

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

【讨论】:

    【解决方案2】:
      // 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;”

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 我不想将输出保存到文件中,我想将其保存到字符串或数组中进行操作。
      • 希望您点击了我提供的链接,因为这两个函数 用于保存到任何文件。这两个都只是将内容返回到一个字符串中。
      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2015-02-06
        • 1970-01-01
        • 1970-01-01
        • 2011-08-28
        • 2013-01-14
        • 1970-01-01
        • 2019-10-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多