首页 文章

HTML表格到PHP数组,带有属性colspan和rowspan

提问于
浏览
0

我需要将HTML表(行和列)转换为PHP数组 . 例如:

<tr>
   <th rowspan="2">Username</th>
   <th colspan="2">Personal</th>
</tr>
<tr>
    <th>Name</th>
    <th>Birth date</th>
</tr>

在PHP中,我需要它成为:

array(
     [0] => array(
                 [0] => array(
                             ["value"] => "Username", 
                             ["rowspan"] => "2"),
                 [1] => array(
                             ["value"] => "Personal", 
                             ["colspan"] => "2")
                 ),
     [1] => array(
                 [0] => array(
                             ["value"] => "Name"
                             ),
                 [1] => array(
                             ["value"] => "Birth date"
                             )
                 )
);

所以,我的想法是,第一个数组将保留行,在每行中我想要一个列数组和列内部我想要一个具有单元格和属性值的数组,我只需要像rowspan这样的属性和colspan . 所以,如果你有了这个想法并且知道如何去做,请分享,我不需要你为我做,我只需要知道我该怎么做 .

2 回答

  • 0

    你应该使用数组的组合

    array(
           array("rowspan"=>3,"colspan=>"2","class"=>"abc",id=>"row_1","value"=>array(1,2)
          );
    

    第一个数组包含用于attriubtes的数组和用于显示数据的value数组

  • 0

    解决方案(2013年3月1日)

    所以,这是解决方案:首先我发送一个包含html表标签的字段的表单 . 然后我得到包含html的字符串,我正在使用symfony,所以在我的操作中我写道: $stringHeader = $request->getParameter('htmlTable'); htmlTable是包含html表格的字段(输入)的名称然后我将字符串转换为XML做:

    $xmlstring = <<<XML
    <?xml version='1.0'?> 
    <document>
    $stringHeader
    </document>
    XML;
    

    最后把数据放到数组中,html的结构如上所述 .

    $xml = simplexml_load_string($xmlstring);
    $header = array();
    $columns = array();
    foreach ($xml->tr as $tr) {
        foreach ($tr->th as $th) {
            if (isset($th->attributes()->rowspan)) {
                $rowspan = $th->attributes()->rowspan;
                $columns[] = array("value" => "$th", "rowspan" => "$rowspan");
            } elseif (isset($th->attributes()->colspan)) {
                $colspan = $th->attributes()->colspan;
                $columns[] = array("value" => "$th", "colspan" => "$colspan");
            } else {
                $columns[] = array("value" => "$th");
            }
    
        }
        $header[] = $columns;
        unset($columns);
        $columns = array();
    }
    

相关问题