PHP - DOM提取锚元素的一部分

时间:2013-12-30 08:30:34

标签: php regex dom

不需要第一个td。如果我循环可以枚举单元格吗?然后选择例如td 1

// [Download simple_html_dom.php][1]
include "simple_html_dom.php";
$table = '<table>
 <tr bgcolor="#F3F3F3" height="22" style="height:25px">

// The first  td not needed          
<td width="20"></td>

// The second td need the node value. 
<td width="295" ><a href="/projecten/482039/N1.asp">a needed cell 1</a>      
</td>   

// The third td need the user from it.
<td width="90"><center><a href="?p=companyprofile&user=abcd" target="_blank"></a>   
</center></td>       



   //*******************************************************************************
   //and so on and so on till eod   

   <tr bgcolor="#FFFFFF" height="22" style="height:25px">
   <td width="20"></td>
   <td width="295" ><a class="d_link" href="/projecten/482320/xxx.asp">xxx</a></td>
   <td width="90"><center><a href="?p=companyprofile&user=yyyyy"         
    target="_blank"></a></center></td>    <td width="120" ><span     
    class="d_tekst">Brussel</span></td>    <td width="65" ><span 
    class="d_tekst">13:54</span></td>    <td width="120" ><font face="Verdana" </small>
    color="#808080"><small><small>0  &nbsp;(<font color="#008080">nieuw project</font>)     
    </small>        </font></td></tr>    

</table>';

$html = str_get_html($table);



header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=sample.csv');

$fp = fopen("php://output", "w");

foreach($html->find('tr') as $element)
{ 
    $td = array();

 //foreach( $element->find('td') as $row)  
 //there must be another way
 //I want to read them one bij one. 
 //Well the fields are put in the array.  


{
        $td [] = $row->plaintext;
    }
    fputcsv($fp, $td);
}


fclose($fp);

问题我需要提取标记名和节点值,我需要将它们保存在一起。 因此第1行中的用户对应于第一行中的其他字段。例如项目。


2 个答案:

答案 0 :(得分:1)

这样做......

<?php
$html='<td><a href="?p=companyprofile&user=abcd" target="_blank"></a></td>';
$dom = new DOMDocument;
@$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $tag) {
        parse_str($tag->getAttribute('href'));

}
echo $user; //"prints" abcd

答案 1 :(得分:-1)

我会使用jquery,http://jquery.com来做到这一点。

    $(document).ready(function(){
        var userArray = new Array();
        $('a').each(function(){
             var href_text = $(this).attr('href');
             if( href_text.indexOf('user=')>=0 ){
                  var index_of_username = href_text.indexOf('user=') + 5;
                  var user_name = href_text.substring(index_of_username);
                  userArray.push(user_name);
             }
        });
        //console.log(userArray);
    });

用你的阵列做任何你想做的事。删除对console.log的注释,以便在调试模式下查看数组输出。