【问题标题】:PHPWord fill .docx template with mysql table dataPHPWord 用 mysql 表数据填充 .docx 模板
【发布时间】:2015-10-17 18:56:02
【问题描述】:

感谢您访问我的帖子,我是 php 编程的新手,目前我正在尝试制作一个允许用户制作汽油券的 Web 应用程序。 这要归功于将数据存储在 mysql 数据库中的多个 Web 表单和动态选项列表。我正在尝试做的是从数据库中获取将位于每个优惠券中的信息,并替换我在单词模板中定义的变量。

实际上,应用程序允许用户制作一张优惠券(它的作用是从表单和列表中获取信息,并使用 POST 方法替换 php 代码中的变量。)

我真的希望有人可以帮助我,因为这就是我完成申请所需的全部内容

Here's a picture of the coupons

这是我的 php 和 html 代码。

vales.html

<html>
<head>
<title>Creaci&oacute;n de Vales</title>
<script type="text/javascript" src="dynamicoptionlist.js"></script>
<link rel="icon" type="image/png" href="favicon.png">
<link rel="stylesheet" href="estilos.css">
</head>
<body onLoad="initDynamicOptionLists()">
<header>
<div class="menu">
    <div class="contenedor">
        <div class="logo">
            <a href="index.html">Creaci&oacute;n de vales</a>
        </div>
        <nav>
        <ul>
        <li><a href="index.html">Inicio</a></li>
        <li><a href="altas.html">Creaci&oacute;n de vales</a></li>
        <li><a href="../graph2/index.php">Consulta de gr&aacute;ficas</a></li>
        <li><a href="extras.html">Vales Extras</a></li>
        </ul>
        </nav>
    </div>
</div>
</header>
<center>
    <div class="Shield">
        <img src="shield.png" width="150px" height="150px">
    </div>
<div class="CV">
    <h1>Creaci&oacute;n de Vales</h1>
</div>
<div class="formu">
<form action="template.php" method="post">
<b>Nombre:&nbsp;Presidencia Municipal</b><br><br>
<b>Departamento:</b>
<select name="dpto">
<!--<option value="Default"></option>-->
<option value="Seguridad">Seguridad</option>
<option value="Servicios Primarios">Servicios Primarios</option>
<option value="Ecologia">Ecolog&iacute;a</option>
<option value="Desarrollo Rural">Desarrollo Rural</option>
<option value="Desarrollo Social">Desarrollo Social</option>
<option value="Presidencia">Presidencia</option>
<option value="Fomento Civico">Fomento Civico</option>
<option value="Regidores">Regidores</option>
<option value="Recursos Humanos">Recursos Humanos</option>
<option value="Tesoreria">Tesorer&iacute;a</option>
<option value="Gestoria">Gestor&iacute;a</option>
<option value="Parques y Jardines">Parques y Jard&iacute;nes</option>
<option value="Contraloria">Contralor&iacute;a</option>
<option value="Alumbrado Publico">Alumbrado P&uacute;blico</option>
<option value="Juridico">Jur&iacute;dico</option>
<option value="Obras Publicas">Obras P&uacute;blicas</option>
<option value="Comunicacion Social">Comuniaci&oacute;n Social</option>
<option value="DIF">DIF</option>
<option value="Biblioteca">Biblioteca</option>
<option value="Secretaria del Ayuntamiento">Secretar&iacute;a del Ayuntamiento</option>
<option value="Proteccion Civil">Protecci&oacute;n Civil</option>
<option value="Bomberos">Bomberos</option>
<option value="Turismo Municipal">Turismo Municipal</option>
<option value="Union de Pensionados">Uni&oacute;n de Pensionados</option>
<option value="SEDENA Ejercito Mexicano">SEDENA Ejercito Mexicano</option>
<option value="Instituto de la Juventud">Instituto de la Juventud</option>
<option value="Centro de Salud">Centro de Salud</option>
<option value="Apoyo Cam 10">Apoyo Cam 10</option>
<option value="Apoyo estudiantes Ejido La Cecilia CBTA">Apoyo estudiantes Ejido La Cecilia CBTA</option>
<option value="Apoyo Atencion Medica Oficial de Seguridad">Apoyo Atenci&oacute;n M&eacute;dica Oficial de Seguridad</option>
<option value="Apoyo EMSAD 28 de Agosto">Apoyo EMSAD 28 de Agosto</option>
<option value="Apoyo estudiantes ejido el Durazno">Apoyo estudiantes ejido el Durazno</option>
<option value="Apoyo estudiantes ejido Ganivete">Apoyo estudiantes ejido Ganivete</option>
<option value="Apoyo estudiantes ejido Estacion Madero">Apoyo estudiantes ejido Estaci&oacute;n Madero</option>
</select><br><br>
<b>Responsable:</b>
<select name="rsp">
</select><br><br>
<b>Fecha:</b><br><br>
D&iacute;a:
<input type="text" size="5" placeholder="15" name="dia">&nbsp;&nbsp;
Mes:
<input type="text" size="5" placeholder="9" name="mes">&nbsp;&nbsp;
A&ntilde;o
<input type="text" size="5" placeholder="2015" name="year"><br><br>&nbsp;&nbsp;
<b>Cantidad:</b>
<input type="text" size="5" placeholder="40" name="cantn">&nbsp;&nbsp;&nbsp;&nbsp;
<b>Cantidad Letra:</b>
<input type="text" size="12" placeholder="Cuarenta" name="cantl"><br><br>
<b>Art&iacute;culo:</b>&nbsp;&nbsp;<i>Litros</i>&nbsp;&nbsp;
<b>Importe:</b>
<select name="imp">
    <option>Magna
    <option>Premium
    <option>Diesel
</select>&nbsp;&nbsp;
<b>Precio:<b>
<select name="precio">
</select><br><br>
<b>Seleccione o ingrese Unidad:</b><br><br>
<select name="uni">
</select><br><br>
<input type="text" size="25" placeholder="Camion de pasajeros" name="uni2"><br><br>
<b>Seleccione o ingrese placas:</b><br><br>
<select name="placas">
</select><br><br>
<input type="text" size="12" placeholder="EXO9843" name="placas2"><br><br>
<input type="submit" value="Registrar">&nbsp;&nbsp;&nbsp;
<input type="reset" value="Limpiar Formularios">
</div>
//This is the code for the dynamicoptions select inputs
<script type="text/javascript">
var names = new DynamicOptionList();
var precio = new DynamicOptionList();

precio.addDependentFields("imp","precio");

precio.forValue("Magna").addOptions("13.57");
precio.forValue("Premium").addOptions("14.50");
precio.forValue("Diesel").addOptions("14.2");

names.addDependentFields("dpto","rsp","uni","placas");
names.forValue("Seguridad").addOptions("Lic. xxxxxx xxxxx xxxx","xxxxx xxxxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx");
names.forValue("Servicios Primarios").addOptions("xxxxx xxxxx xxxxx");
names.forValue("Ecologia").addOptions("xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx");
names.forValue("Desarrollo Rural").addOptions("xxxxx xxxxx xxxxx");
names.forValue("Desarrollo Social").addOptions("xxxxx xxxxx xxxxx");
names.forValue("Presidencia").addOptions("xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx");
names.forValue("Fomento Civico").addOptions("xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx");

</script>

模板.php

<?php
require_once dirname(__FILE__).'/PHPWord-master/src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();

use PhpOffice\PhpWord\TemplateProcessor;


$total = $_REQUEST[cantn] * $_REQUEST[precio];


$conexion=mysql_connect("localhost","root","") or
  die("Problemas en la conexion");
mysql_select_db("presi",$conexion) or
  die("Problemas en la seleccion de la base de datos");
mysql_query("insert into vales(dpto,rsp,cantn,imp,precio,uni,placas,placas2) values ('$_REQUEST[dpto]','$_REQUEST[rsp]','$_REQUEST[cantn]','$_REQUEST[imp]','$total','$_REQUEST[uni]','$_REQUEST[placas]','$_REQUEST[placas2]')", $conexion) or
  die("Problemas en el select".mysql_error());
mysql_close($conexion);

$templateWord = new TemplateProcessor('plantilla.docx');

//$nombre = $_REQUEST['nombre'];
$folio = $_GET['id'];
$departamento = $_REQUEST['dpto'];
$responsable = $_REQUEST['rsp'];
$dia = $_REQUEST['dia'];
$mes = $_REQUEST['mes'];
$year = $_REQUEST['year'];
$cantn = $_REQUEST['cantn'];
$cantl = $_REQUEST['cantl'];
//$articulo = $_REQUEST['articulo'];
$importe = $_REQUEST['imp'];
$unidad = $_REQUEST['uni'];
$placas = $_REQUEST['placas'];


// --- Asignamos valores a la plantilla
//$templateWord->setValue('nombre',$nombre);
$templateWord->setValue('folio',$folio);
$templateWord->setValue('departamento',$departamento);
$templateWord->setValue('responsable',$responsable);
$templateWord->setValue('dia',$dia);
$templateWord->setValue('mes',$mes);
$templateWord->setValue('year',$year);
$templateWord->setValue('cantn',$cantn);
$templateWord->setValue('cantl',$cantl);
//$templateWord->setValue('articulo',$articulo);
$templateWord->setValue('importe',$importe);
$templateWord->setValue('unidad',$unidad);
$templateWord->setValue('placas',$placas);


// --- Guardamos el documento
ob_clean();
$templateWord->saveAs('Vales.docx');

header("Content-Disposition: attachment; filename=Vales.docx; charset=iso-8859-1");
echo file_get_contents('Vales.docx');
?>

谢谢你的时间,对不起我的英语不好。

【问题讨论】:

  • 你很容易受到sql injection attacks
  • 如果您澄清一下您的问题实际上是什么,这可能会有所帮助(写入 db 失败,创建 word 文档失败,代码中的某些内容失败,您不知道)。除了 sql 注入攻击漏洞之外,您还有明显的错误,例如在设置 $total 值(缺少用于获取请求值的引号)并且您的示例 html 没有任何值(选项)用于几个选择输入(空选择 => $_REQUEST 数组不包含密钥,您会从 php 处理中得到错误)
  • 感谢您的评论,我将尝试纠正漏洞,@ejuhjav 应用程序运行良好,写入 db 或创建文档时没有任何问题。如您所见,我只取一次值(我的意思是从表格中)并将它们放入单词模板中,我需要将值放入数据库中并将它们放入模板中,这样可以创建多个优惠券,因为目前我只能创建一张优惠券。
  • 对于选择输入,我使用了一个名为 DynamicOptionLists 的脚本,它允许我创建内容取决于父框的值的选择框。我正在编辑帖子,让您使用此脚本查看我的所有 html 代码

标签: php mysql while-loop phpword


【解决方案1】:

好的 - 如果这次我理解正确,即您需要将所有优惠券打印到单个 word 文件中(?)如果您正在考虑为每个优惠券创建多个 word 文件,那么您只需要获取所有db 数据并使用模板创建单个单词文件(正如您已经在做的那样),将所有创建的优惠券文件存储在服务器中的某个位置,将文件打包成单个文件(zip 或其他文件)并将该文件提供给用户.. .

所以,对于在单字文件中创建优惠券的情况:

首先,您需要稍微修改一下您的 word 模板:在您希望为每张优惠券克隆的区域周围添加所需的模板标签(在本例中名为 CLONEME 的开始和结束标签),例如:

${CLONEME}
Here is your normal single coupon template fields, i.e.
${folio}
${departamento}
...
$(/CLONEME}

您可以使用以下方式处理插入到您的 word 模板中的数据:

// first fetch your coupons from the db
$result = mysql_query("SELECT * FROM vales", $conexion);
if(!$result) 
{
    die("Database query failed: " . mysql_error());
}

// then get your template and clone the coupon block for each of the results
$templateWord = new TemplateProcessor('plantilla.docx');
$templateWord->cloneBlock('CLONEME', mysql_num_rows($result));

// loop over your results and fill the template values
while ($row = mysql_fetch_array($result))
{
    // NOTE! add the 1 parameter to each setValue so that it replaces only
    // one template field at time (after cloning the block the template
    // contains several same named template fields - for each coupon that is)
    $templateWord->setValue("departamento", $row["dpto"], 1);
    // ... similarly the other values...
}

// and last, store the word result etc

【讨论】:

  • 感谢您的回复,您说得对,我想在一个 word 文件中创建多张优惠券,很抱歉,但我真的需要您的帮助,我明白您告诉我要做什么,但在我的模板 y 有多个应该是优惠券的表,例如,在第一个表中,我有将针对数据库值更改的字段,所以我需要做的是打开 ${CLONEME} 标记,其中第一个字段在最后一个字段中开始和结束(在本例中为 ${unidad})?我在其他桌子上放了什么?对不起,我是一个真正的新手,我会非常感谢你的帮助
  • 我编辑了帖子并添加了一个指向优惠券图片的链接,希望您不要介意打开它。再次感谢
  • 好的,我试过了!非常感谢,真的!我已经被困在这里大约一个月了
  • 我不认为你可以放入一个数组,并设置这样的限制,认为应该是$templateWord-&gt;setValue('search_phrase', 'Replace By Text', 1);
  • 感谢@Richard。参数$row["dpto"] 是示例中的字符串而不是数组 - 但是,您是正确的,在那里的 setValue 函数调用中似乎缺少“search_phrase”。我已经相应地更新了答案。
猜你喜欢
  • 2023-01-04
  • 2018-04-13
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多