【问题标题】:HTML Table to PHP array with atributes colspan and rowspan具有属性 colspan 和 rowspan 的 HTML 表到 PHP 数组
【发布时间】:2013-02-12 05:54:24
【问题描述】:

我需要将 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 等属性。所以如果你有这个想法并且知道怎么做,请分享,我不需要你为我做,我只需要知道我该怎么做。

【问题讨论】:

  • 你为什么要做某事?你喜欢做什么?
  • 我不知道您所说的“转换”是什么意思您是否要将此 HTML 解析为 PHP? HTML 是否代表 POST 到 PHP 的数据?
  • 在javascript中转成json或者xml,然后发送到php中。
  • 我开发了一种方法,它接收这种类型的数组,然后使用 PHPExcel 将值写入 excel 文件。这个想法是,我在运行时生成了报告,所以,字段是动态选择的,我不能使用 PHPExcel 做一个静态模板,所以,我找到了一个使用数组的解决方案,并测试了这个数组作为我的方法的输入效果很好,我会改进方法。但现在我必须知道如何将这个 Html 作为一个数组来获取。将 html 传递给 php 脚本不是问题我想要将这个 html 解析为数组的想法。
  • 也许这个链接会帮助你stackoverflow.com/questions/15684780/…

标签: php html arrays html-table


【解决方案1】:

你应该使用类似数组的组合

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

第一个数组包含属性数组和显示数据的值数组

【讨论】:

    【解决方案2】:

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

    所以,这里是解决方案: 首先,我发送一个表单,其中包含一个包含 html 表格标签的字段。 然后我得到包含 html 的字符串,我用 symfony 来做,所以在我的操作中我写道: $stringHeader = $request-&gt;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();
    }
    
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 2018-09-11
    • 2013-03-05
    • 1970-01-01
    相关资源
    最近更新 更多