how to optimize this code for webcrawler? - php

I'm practicing webcrawler and I need to optimize this code, I'm a beginner and I wrote this code , I feel it is very slow, how could I optimize it?
Briefly, I want to get the pages of this e-comerce, and filter the discounts and cashbacks that I will define.
Please give me suggestions.
thankful!
already tried as libs
simpledomparser guzzle and PHPHtmlParser, I also tried going through cURL and file_get_contents
<?php
require "vendor/autoload.php";
use PHPHtmlParser\Dom;
echo 'INICIANDO<br/>';
$ame = 15;
$discount = 15;
$busca = 'https://www.shoptime.com.br/lojista/b2w';
$padraoPagina = 2; //1 é soma 24 , 2 é padrão 'pagina-1'
$numPaginaMax = 5000; //valor a ser imputado para o numero maximo de paginas a ser buscado
$offset = 24;
$numPagina = 0;
function soNumero($str) {
return preg_replace("/[^0-9]/", "", $str);
}
for ($i = 1; $i <= $numPaginaMax; $i++) {
$url = $busca;
if ($padraoPagina == 1) {
$i == 1 ? $numPagina = 0 : $numPagina += $offset; //usando operador ternario (praticando)
$url .= "?limite=24&offset=".$numPagina;
}
else { //diferente de $padraoPagina ==1
$numPagina = '/pagina-'.$i;
$url .= "$numPagina";
}
$html = new Dom;
foreach ($html->loadFromUrl($url)->find('a.card-product-url') as $ref2) {
$url_produto_localizado = 'https://www.shoptime.com.br'.$ref2->getAttribute('href');
unset($html);
$html2 = new Dom;
$html2->loadFromUrl($url_produto_localizado);
$discountProd = $html2->find('span.discount',0); // desconto no produto
if (!empty($discountProd)) { //testar ($discountProd !== null) e colocar ternario
$discountProd = soNumero($discountProd->plaintext);
}
$amePorcText = $html2->find('span.hMwkMY',0)."<br/>";
$pos1 = strpos($amePorcText, '(');
$pos2 = strpos($amePorcText, '%');
$ameReal = substr($amePorcText, $pos1+1, ($pos2-$pos1)-1);
if ($ameReal >= $ame or $discountProd >= $discount) {
if ($ameReal >=$ame) {
echo "<br/><b><br/>❤️ Opa, cashback de $ameReal% ❤️<br/></b>";
}
if ($discountProd >= $discount) {
echo " 💰 Desconto de $discountProd% 💰<br/>" ;
}
echo $html2->find('h1.gzujnn',0)->text.'</br>'; //mostra o produto dentro da condição master rs
echo "<a href='$url_produto_localizado' target='_blank'>ABRIR PRODUTO</a> da pagina $i<br/><br/>";
}
else {
echo " ☹️ ";
}
unset($html2); //limpar memoria
}
}

Related

Do I need extention to enable for XML /XSLT as I am getting this error too i.e MySQL server version for the right syntax to use near '' at line 1

I have this set of code and what I am getting is this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
I am unable to figure it out what exactly the issue is...Do I need to enable some extention in my server..or whay
here is the link of the exact script:
http://cfactura.info/jorgemiron/nomina/n5.php
<?php
include('../Connections/conexion.php');
$id = $_GET['id'];
$sql = "SELECT N.*,N.RFC 'rfc1', E.*
FROM nomina N
JOIN empresa E ON (E.id = N.idEmpresa)
WHERE N.id =".$_GET['id'];
//$sql = "select * from nomina where id='".$_GET["id"]."'";
//echo $sql;
//echo $sql; die();
$res = mysql_query($sql) or die(mysql_error());
//exit;
$row = mysql_fetch_assoc($res);
//$row['rfc1'] = substr($row['rfc1'],0,strlen($row['rfc1'])-1);
//echo $row['rfc1'];
//die();
$sqlFolios = "SELECT * FROM folios_asignados WHERE (id_empresa = ".$row['idEmpresa'].")";
//echo $sqlFolios;
$resFolios = mysql_query($sqlFolios) or die(mysql_error());
$rowFolios = mysql_fetch_assoc($resFolios);
##########################################################
# PASO1. Crea un CFDi de nomina
#
# Regresa un texto en la variable $cfdi
##########################################################
# Partimos de un CFDi a medias, conservando declaracion de esquemas
$fecha = substr($row['fecha_emision'], 0, -6);
//echo "<pre>";print_r($fecha);die;
$cfdi = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:nomina="http://www.sat.gob.mx/nomina" xmlns:ecb="http://www.sat.gob.mx/ecb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:implocal="http://www.sat.gob.mx/implocal" xmlns:bfa2="http://www.buzonfiscal.com/ns/addenda/bf/2" xmlns:terceros="http://www.sat.gob.mx/terceros" xmlns:detallista="http://www.sat.gob.mx/detallista" xmlns:psgecfd="http://www.sat.gob.mx/psgecfd" xmlns:ecc="http://www.sat.gob.mx/ecc" xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital" version = "3.2" folio = "" fecha = "$fecha" sello = "" formaDePago = "" noCertificado="00001000000302229462" certificado = "" subTotal="0.00" descuento="0.00" motivoDescuento="Deducciones nomina" total="0.00" tipoDeComprobante="egreso" metodoDePago="" LugarExpedicion="" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/TimbreFiscalDigital/TimbreFiscalDigital.xsd http://www.sat.gob.mx/detallista http://www.sat.gob.mx/sitio_internet/cfd/detallista/detallista.xsd http://www.sat.gob.mx/implocal http://www.sat.gob.mx/sitio_internet/cfd/implocal/implocal.xsd http://www.buzonfiscal.com/ns/addenda/bf/2 http://www.buzonfiscal.com/schema/xsd/Addenda_BF_v2.2.xsd http://www.sat.gob.mx/nomina
http://www.sat.gob.mx/sitio_internet/cfd/nomina/nomina12.xsd">
<cfdi:Emisor nombre="OFELIA DAVILA IBARRA" rfc="DAIO630114T46">
<cfdi:DomicilioFiscal codigoPostal="" pais="Mexico" estado="" municipio="" calle="" colonia="" localidad="" />
<cfdi:RegimenFiscal/>
</cfdi:Emisor>
<cfdi:Receptor rfc="">
</cfdi:Receptor>
<cfdi:Conceptos>
</cfdi:Conceptos>
<cfdi:Impuestos>
<cfdi:Traslados>
<cfdi:Traslado importe="" tasa="16.00" impuesto="IVA"/>
</cfdi:Traslados>
</cfdi:Impuestos>
<cfdi:Complemento>
</cfdi:Complemento>
</cfdi:Comprobante>
XML;
//$cfdi = preg_replace("/\[RFC\]/",$row["rfc1"],$cfdi);
# Convierte a objeto DOM $xml
$xml = new DOMDocument();
$xml->loadXML($cfdi);
$xmlcomprobante = $xml->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'Comprobante')->item(0);
if (strlen(trim($row['serie'])) > 0) {
$xmlcomprobante->setAttribute('serie', trim($row['serie']));
}
//$xmlcomprobante->setAttribute('folio', $row['numero']);
$xmlcomprobante->setAttribute('folio',$id);
$xmlcomprobante->setAttribute('formaDePago', trim($row['forma_pago_sat']));
$xmlcomprobante->setAttribute('metodoDePago', trim($row['metodo_pago']));
$xmlcomprobante->setAttribute('LugarExpedicion', trim($row['expedicion']));
if ($row['numctapago'] != NULL)
{
$xmlcomprobante->setAttribute('NumCtaPago', $row['numctapago']);
}
$xmlemisor = $xml->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'Emisor')->item(0);
$xmlemisordomicilio = $xmlemisor->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'DomicilioFiscal')->item(0);
$xmlemisordomicilio->setAttribute('codigoPostal', trim($row['zip']));
$xmlemisordomicilio->setAttribute('pais', utf8_encode(trim($row['pais'])));
$xmlemisordomicilio->setAttribute('estado', utf8_encode(trim($row['estado'])));
$xmlemisordomicilio->setAttribute('municipio', utf8_encode(trim($row['municipio'])));
$xmlemisordomicilio->setAttribute('calle', utf8_encode(trim($row['domicilio'])));
$xmlemisordomicilio->setAttribute('colonia', utf8_encode(trim($row['colonia'])));
$xmlemisordomicilio->setAttribute('localidad', utf8_encode(trim($row['ciudad'])));
unset($xmlemisordomicilio);
//echo utf8_encode(trim($row['ciudad']));die;
$xmlemisorregimen = $xmlemisor->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'RegimenFiscal')->item(0);
$xmlemisorregimen->setAttribute('Regimen', trim($row['regimen']));
unset($xmlemisorregimen);
unset($xmlemisor);
# Modifica codigos semifijos
$xmlreceptor = $xml->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'Receptor')->item(0);
$receptornombre = utf8_encode(trim($row['nombre']) . " " . trim($row['apellido_paterno']) . " " . trim($row['apellido_materno']));
if (strlen($receptornombre) > 0) {
$xmlreceptor->setAttribute('nombre', $receptornombre);
//echo $receptornombre;die;
}
//print_r($receptornombre);die;
$maxreceptorrfclen = 13;
$receptorrfc = utf8_encode(trim($row['rfc1']));
if (strlen($receptorrfc) > $maxreceptorrfclen) {
$receptorrfc = substr($receptorrfc, 0, $maxreceptorrfclen);
}
$xmlreceptor->setAttribute('rfc', $receptorrfc);
unset($xmlreceptor);
# Agrega concepto
$xmlconceptos = $xml->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'Conceptos')->item(0);
$xmlconcepto = $xml->createElementNS('http://www.sat.gob.mx/cfd/3', 'Concepto');
$xmlconcepto->setAttribute('cantidad', 1);
$xmlconcepto->setAttribute('unidad', 'Servicio');
$xmlconcepto->setAttribute('descripcion', 'Sueldo');
$xmlconcepto->setAttribute('valorUnitario', number_format($row['total'], 2, '.', ''));
$xmlconcepto->setAttribute('importe', number_format($row['total'], 2, '.', ''));
$xmlconceptos->appendChild($xmlconcepto);
unset($xmlconcepto);
$c = $xml->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'Comprobante')->item(0);
$c->getElementsByTagName('Impuestos')->item(0)->getElementsByTagName('Traslados')->item(0)->getElementsByTagName('Traslado')->item(0)->setAttribute('importe', $row['iva']);
# Agrega nodo nomina
$xmlcomplemento = $xml->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'Complemento')->item(0);
$xmlNomina = $xml->createElementNS('http://www.sat.gob.mx/nomina12', 'Nomina');
$xmlNomina->setAttribute('Version', 1.2);
//$xmlNomina->setAttribute('RegistroPatronal', $row['registroPatronal']);
//$xmlNomina->setAttribute('NumEmpleado', $row['numEmpleado']);
//$xmlNomina->setAttribute('Curp', $row['CURP']);
//$xmlNomina->setAttribute('TipoRegimen', $row['tipoRegimen']);
if ($row['imss'] != NULL)
{
$xmlNomina->setAttribute('NumSeguridadSocial', $row['imss']);
}
$xmlNomina->setAttribute('FechaPago', $row['FechaPago']);
$xmlNomina->setAttribute('FechaInicialPago', $row['FechaInicialPago']);
$xmlNomina->setAttribute('FechaFinalPago', $row['FechaFinalPago']);
//$xmlNomina->setAttribute('NumDiasPagados', $row['numDiasPagados']);
$xmlNomina->setAttribute('NumDiasPagados', 30);
if ($row['Departamento'] != NULL)
{
$xmlNomina->setAttribute('Departamento', $row['Departamento']);
}
if ($row['clabe'] != 0)
$xmlNomina->setAttribute('CLABE', $row['clabe']);
//if ($row['banco'] != 0)
// $xmlNomina->setAttribute('Banco', $row['banco']);
//if ($row['FechaIniRelLaboral'] != '0001-01-01')
// $xmlNomina->setAttribute('FechaInicioRelLaboral', $row['FechaIniRelLaboral']);
if ($row['antiguedad'] != 0)
{
//$xmlNomina->setAttribute('Antiguedad', $row['antiguedad']);
}
if ($row['puesto'] != NULL)
{
//$xmlNomina->setAttribute('Puesto', $row['puesto']);
}
if ($row['tipoContrato'] != NULL)
{
//$xmlNomina->setAttribute('TipoContrato', $row['tipoContrato']);
}
if ($row['tipoJornada'] != NULL)
{
//$xmlNomina->setAttribute('TipoJornada', $row['tipoJornada']);
}
//$xmlNomina->setAttribute('PeriodicidadPago', $row['periodicidadPago']);
if ($row['salariobase'] != 0)
{
//$xmlNomina->setAttribute('SalarioBaseCotApor', $row['salariobase']);
}
if ($row['riesgoPuesto'] != 0)
{
//$xmlNomina->setAttribute('RiesgoPuesto', $row['riesgoPuesto']);
}
if ($row['departmento'] != 0)
{
$xmlNomina->setAttribute('Departamento', $row['departmento']);
}
//$xmlNomina->setAttribute('CLABE', $row['clabe']);
//echo "....".$row['SalarioDiarioIntegrado'].".....";
//$xmlNomina->setAttribute('SalarioDiarioIntegrado', number_format($row['salarioDiarioIntegrado'],2,'.',''));
//Busco las percepciones
$sql2 = "SELECT * FROM percepciones WHERE (idNomina = " . $_GET['id'] . ")";
$res2 = mysql_query($sql2);
$totPercepcion = 0;
if (mysql_num_rows($res2) > 0)
{
$totalg = $totale = 0;
$xmlPercepciones = $xml->createElementNS('http://www.sat.gob.mx/nomina', 'Percepciones');
while ($row2 = mysql_fetch_assoc($res2))
{
$xmlPercepcion = $xml->createElementNS('http://www.sat.gob.mx/nomina', 'Percepcion');
$totalg = $totalg + $row2['ImporteGravado'];
$totale = $totale + $row2['ImporteExento'];
$xmlPercepcion->setAttribute('TipoPercepcion', str_pad($row2['TipoPercepcion'],3,"0",STR_PAD_LEFT));
$xmlPercepcion->setAttribute('Clave', str_pad($row2['Clave'],3,"0",STR_PAD_LEFT));
$xmlPercepcion->setAttribute('Concepto', $row2['Concepto']);
$xmlPercepcion->setAttribute('ImporteGravado', $row2['ImporteGravado']);
$xmlPercepcion->setAttribute('ImporteExento', $row2['ImporteExento']);
$xmlPercepciones->appendChild($xmlPercepcion);
}
$xmlPercepciones->setAttribute('TotalGravado', $totalg);
$xmlPercepciones->setAttribute('TotalExento', $totale);
$xmlNomina->appendChild($xmlPercepciones);
}
$totPercepcion = $totalg + $totale;
/*
//Busco las deducciones
$sql3 = "SELECT * FROM deducciones WHERE (idNomina = " . $_GET['id'] . ")";
$res3 = mysql_query($sql3);
$totDeducciones = 0;
if (mysql_num_rows($res3) > 0)
{
$totalg = $totale = 0;
$xmlDeducciones = $xml->createElementNS('http://www.sat.gob.mx/nomina', 'Deducciones');
while ($row3 = mysql_fetch_assoc($res3))
{
$xmlDeduccion = $xml->createElementNS('http://www.sat.gob.mx/nomina', 'Deduccion');
$totalg = $totalg + $row3['ImporteGravado'];
$totale = $totale + $row3['ImporteExento'];
$xmlDeduccion->setAttribute('TipoDeduccion', str_pad($row3['TipoDeduccion'],"3","0",STR_PAD_LEFT));
$xmlDeduccion->setAttribute('Clave', str_pad($row3['Clave'],"3","0",STR_PAD_LEFT));
$xmlDeduccion->setAttribute('Concepto', $row3['Concepto']);
$xmlDeduccion->setAttribute('ImporteGravado', $row3['ImporteGravado']);
$xmlDeduccion->setAttribute('ImporteExento', $row3['ImporteExento']);
$xmlDeducciones->appendChild($xmlDeduccion);
}
$xmlDeducciones->setAttribute('TotalGravado', $totalg);
$xmlDeducciones->setAttribute('TotalExento', $totale);
$xmlNomina->appendChild($xmlDeducciones);
}
$totDeducciones = $totalg + $totale;
//Busco las incapacidades
$sql4 = "SELECT * FROM incapacidades WHERE (idNomina = " . $_GET['id'] . ")";
$res4 = mysql_query($sql4);
$totIncapacidades = 0;
if (mysql_num_rows($res4) > 0)
{
$xmlIncapacidades = $xml->createElementNS('http://www.sat.gob.mx/nomina', 'Incapacidades');
while ($row4 = mysql_fetch_assoc($res4))
{
$xmlIncapacidad = $xml->createElementNS('http://www.sat.gob.mx/nomina', 'Incapacidad');
$xmlIncapacidad->setAttribute('DiasIncapacidad', $row4['DiasIncapacidad']);
$xmlIncapacidad->setAttribute('TipoIncapacidad', $row4['TipoIncapacidad']);
$xmlIncapacidad->setAttribute('Descuento', $row4['Descuento']);
$xmlIncapacidades->appendChild($xmlIncapacidad);
$totIncapacidades = $totIncapacidades + $row4['Descuento'];
}
$xmlNomina->appendChild($xmlIncapacidades);
}
//Busco las HorasExtra
$sql5 = "SELECT * FROM horasExtras WHERE (idNomina = " . $_GET['id'] . ")";
$res5 = mysql_query($sql5);
$totHorasExtra = 0;
if (mysql_num_rows($res5) > 0)
{
$xmlHorasExtras = $xml->createElementNS('http://www.sat.gob.mx/nomina', 'HorasExtras');
while ($row5 = mysql_fetch_assoc($res5))
{
$xmlHorasExtra = $xml->createElementNS('http://www.sat.gob.mx/nomina', 'HorasExtra');
$xmlHorasExtra->setAttribute('Dias', $row5['dias']);
$xmlHorasExtra->setAttribute('TipoHoras', $row5['tipoHoras']);
$xmlHorasExtra->setAttribute('HorasExtra', $row5['horasExtra']);
$xmlHorasExtra->setAttribute('ImportePagado', $row5['ImportePagado']);
$xmlHorasExtras->appendChild($xmlHorasExtra);
$totHorasExtra = $totHorasExtra + $row5['ImportePagado'];
}
$xmlNomina->appendChild($xmlHorasExtras);
}
//Totalizo los importes
$descuentos = number_format(($totDeducciones + $totIncapacidades), 2, '.', '');
$xmlcomprobante->setAttribute('descuento', $descuentos);
$xmlcomprobante->setAttribute('subTotal', number_format($totPercepcion + $totHorasExtra, 2, '.', ''));
$xmlcomprobante->setAttribute('total', number_format($totPercepcion + $totHorasExtra - $totDeducciones - $totIncapacidades , 2, '.', ''));
*/
$xmlcomplemento->appendChild($xmlNomina);
unset($xmlcomprobante);
unset($xmlNomina);
unset($xmlcomplemento);
# Reconvierte a texto
$cfdi = $xml->saveXML();
###############################################################
# PASO2. Firma el comprobante que esta en $cfdi en modo texto
#
# Regresa el comprobante firmado en la misma variable $cfdi
###############################################################
# Extrae cadena original
$xslt = new XSLTProcessor();
$XSL = new DOMDocument();
$XSL->load('http://www.sat.mx/cfd/3/cadenaoriginal_3_2/cadenaoriginal_3_2.xslt', LIBXML_NOCDATA);
error_reporting(0); # Se deshabilitan los errores pues el xssl de la cadena esta en version 2 y eso genera algunos warnings
$xslt->importStylesheet($XSL);
error_reporting(E_ALL); # Se habilitan de nuevo los errores (se asume que originalmente estaban habilitados)
$c = $xml->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'Comprobante')->item(0);
$cadena = $xslt->transformToXML($c);
unset($xslt, $XSL);
$sql4 = "UPDATE nomina SET cadena_original = '" . $cadena . "' WHERE id = " . $_GET['id'];
$res4 = mysql_query($sql4) or die(mysql_error());
//genero el sello digital
$key = <<<TEXT
-----BEGIN PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIQIhByL3i6IGG+U
JMzMBCTHLsKFXqHVHXHvZCKsXa+WvqjQhJfSbOLOQTkodUjp5m1DUWu5WBkwlRt+
XOXrACkpp7P1iXuQp2+vNgDT7wgj4R/XjZCCXS67Ys3X9/KFB3ou/hR+yyBoobI2
OzOpCYEXGhXHir7kqE3VKaiSIV6FAgMBAAECgYBdBAreeYLrUSG16a4LQWdh6Zj9
nSvP4u29iKMI8lmGDDMBhvUCaFIhbqDwfZoy5eVZ8GT5+Tchd+Jz3g/gQjB3ymsm
X4tOKl0iSwAGTzh9AGCdU1DDd1QiLNTpSXGnOKLB6MDxeA8jrfKN5ayVRuf3V/be
aB3NlzmTPX9Ul6IYQQJBAM8LVbPxKKZPd98d8I/FwthoxytxX20UvBOraCM/sgYP
LKCtqhIEJdQhPfBnLU4OVLLmWu7Rib7f9SPs+ZbYte0CQQCjQKpFRHS6nlaJyP0N
a1ROHIyupixnIu9cnNOIraWQSrHOqVc+5ZZQd3j8CU3rIEQoEBNB31tg2YKmHHUC
/Lf5AkAZTVBO6jTGhkWm7Zi9aTSTj9JvO66mvPbzDGpwjFMsLGSOykpTY1BgKSPR
ojpGJLgzGLWaI99KhUIG/unNhnRNAkBKu4J2vRS2jV9OKez1pKluLJGWLcnr2Mk8
WypWyi8dc6Qb19dxmoYKBfcjYVsDBL1OnbVDFW1uU4QEaMiD+o55AkAXuVNLIUWS
jF+MK65oLyyyrOF4JNsQgEsIZREArWvMyyCMbQPPhPKqVZtjlLJVfMff5hJ27LiL
cSyNyMRM5j5O
-----END PRIVATE KEY-----
TEXT;
// $pass = trim($rowFolios['clave']);
$llave = openssl_pkey_get_private($key);
openssl_sign($cadena, $sello, $llave);
$sello = base64_encode($sello);
$certificado="MIIEnDCCA4SgAwIBAgIUMDAwMDEwMDAwMDAzMDE5NDI3NjQwDQYJKoZIhvcNAQEFBQAwggGKMTgwNgYDVQQDDC9BLkMuIGRlbCBTZXJ2aWNpbyBkZSBBZG1pbmlzdHJhY2nDs24gVHJpYnV0YXJpYTEvMC0GA1UECgwmU2VydmljaW8gZGUgQWRtaW5pc3RyYWNpw7NuIFRyaWJ1dGFyaWExODA2BgNVBAsML0FkbWluaXN0cmFjacOzbiBkZSBTZWd1cmlkYWQgZGUgbGEgSW5mb3JtYWNpw7NuMR8wHQYJKoZIhvcNAQkBFhBhY29kc0BzYXQuZ29iLm14MSYwJAYDVQQJDB1Bdi4gSGlkYWxnbyA3NywgQ29sLiBHdWVycmVybzEOMAwGA1UEEQwFMDYzMDAxCzAJBgNVBAYTAk1YMRkwFwYDVQQIDBBEaXN0cml0byBGZWRlcmFsMRQwEgYDVQQHDAtDdWF1aHTDqW1vYzEVMBMGA1UELRMMU0FUOTcwNzAxTk4zMTUwMwYJKoZIhvcNAQkCDCZSZXNwb25zYWJsZTogQ2xhdWRpYSBDb3ZhcnJ1YmlhcyBPY2hvYTAeFw0xMzEyMjAxNzAyMTdaFw0xNzEyMjAxNzAyMTdaMIHoMS0wKwYDVQQDEyRDT05TVFJVQ0NJT05FUyBNSVJPTiBGTE9SRVMgU0EgREUgQ1YxLTArBgNVBCkTJENPTlNUUlVDQ0lPTkVTIE1JUk9OIEZMT1JFUyBTQSBERSBDVjEtMCsGA1UEChMkQ09OU1RSVUNDSU9ORVMgTUlST04gRkxPUkVTIFNBIERFIENWMSUwIwYDVQQtExxDTUYwMTEyMjY1SDYgLyBMSVZGNzkwOTEzQ0k3MR4wHAYDVQQFExUgLyBMSVZGNzkwOTEzSE5MTkxSMjgxEjAQBgNVBAsTCU1PTlRFUlJFWTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAhAiEHIveLogYb5QkzMwEJMcuwoVeodUdce9kIqxdr5a+qNCEl9Js4s5BOSh1SOnmbUNRa7lYGTCVG35c5esAKSmns/WJe5Cnb682ANPvCCPhH9eNkIJdLrtizdf38oUHei7+FH7LIGihsjY7M6kJgRcaFceKvuSoTdUpqJIhXoUCAwEAAaMdMBswDAYDVR0TAQH/BAIwADALBgNVHQ8EBAMCBsAwDQYJKoZIhvcNAQEFBQADggEBAJB62ojrA3soTeYRIV/loSz0K0bBvYbdQDk39BbxtpheWTDT4cffJAycM6T6+6bamlBQScdo0hi9xUOE3lp5BeRB2dlzGdcekDqfHwKYLX1aEQIayihQcXWrtArbF+u7v/+twiJDSzF4RjAlw/4F7+z/xM+wAuW13T19WfNpJ/IEu02NpTfFd15yh+pnLqxxkEKWmC+w0aj28RvSbK9+fHjqpCxsTCjvxepqTa5Vja4MJfgo/pN+1rGanMlVuHwjSm+piMUnFkyPNPfXbLzx7dRsXNS2kRyC3RnMMAR5DyKsmiiKqBNVOs8TuBfx5JMzRFaDuDlceZpE4dejP0kUKKY=";
# Incorpora los tres elementos al cfdi
$c->setAttribute('certificado', $certificado);
$c->setAttribute('sello', $sello);
# regresa el resultado
$cfdi = $xml->saveXML();
unset($c, $certificado, $sello, $cadena, $key);
###############################################################
# PASO4. Timbra el CFDI en la variable $cfdi con TimbreFiscal
#
# 4.1) Ensobreta
# 4.2) Env?a a TimbreFiscal
# 4.3) Recibe un timbre (o procesa un error)
# Regresa el $cfdi intacto y $timbre
###############################################################
# Convierte a modelo DOM
#$xml = new DOMDocument();
#$xml->loadXML($cfdi) or die("\n\n\nXML no valido");
# Valida CFDi contra esquema
#$xml->schemaValidate('cfdv3.xsd') or die("\n\n\nCFDi no valido");
# Sobre con el request
$envtext = <<<XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cfdi="http://cfdi.service.ediwinws.edicom.com">
<soapenv:Header/>
<soapenv:Body>
<cfdi:getCfdi>
<cfdi:user></cfdi:user>
<cfdi:password></cfdi:password>
<cfdi:file></cfdi:file>
</cfdi:getCfdi>
</soapenv:Body>
</soapenv:Envelope>
XML;
$env = new DOMDocument();
$env->loadXML($envtext) or die("\n\n\nError interno en el sobre");
$req = $env->getElementsByTagNameNS('http://cfdi.service.ediwinws.edicom.com', 'getCfdi')->item(0);
$req->getElementsByTagName('user')->item(0)->nodeValue = "CFO1010219Z8";
$req->getElementsByTagName('password')->item(0)->nodeValue = "gjstbaarg";
$req->getElementsByTagName('file')->item(0)->nodeValue = base64_encode($cfdi);
//echo "<pre>";print_r($env->saveXML());die;
# Paso 4.2 Env?a a TimbreFiscal y 4.3 recibe un timbre o procesa un error
$process = curl_init('https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi');
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: text/xml', 'charset=utf-8', 'SOAPAction: ""'));
curl_setopt($process, CURLOPT_POSTFIELDS, $env->saveXML());
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
curl_setopt($process, CURLOPT_POST, true);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($process, CURLOPT_SSL_VERIFYHOST, false);
$timbre = curl_exec($process);
curl_close($process);
if (!$timbre) {
echo curl_error($process);
die("Error en comunicacion\n");
}
###############################################################
# PASO5. Integra el timbre recibido en $timbre en el $cfdi
#
# Regresa el $cfdi ya integrado con el timbre
###############################################################
# Valida que realmente haya regresado un timbre
$sobretimbre = new DOMDocument();
$sobretimbre->loadXML($timbre) or die("\n\n\nXML de respuesta no valido\n");
# Extrae el timbre (si existe)
$xmltimbre = new DOMDocument('1.0', 'UTF-8');
# Extrae el nodo
if (!$sobretimbre->getElementsByTagNameNS('http://cfdi.service.ediwinws.edicom.com', 'getCfdiReturn')->item(0)) {
//echo "<pre>"; print_r($sobretimbre);die;
$err = $sobretimbre->getElementsByTagName ('faultstring') or die("\n\n\nError de validacion\n$return");
$errStr = "";
foreach ($err as $node) {
$errStr = $node->nodeValue."<br/>";
}
//die("\n\n\n$errStr\n");
echo "ERROR EN EL PROCESO DE TIMBRADO: ".$errStr;
$goto = "index.php";
echo "<p><input name='submit' type='button' value='Finalizar' onClick='javascript: window.location.href=\"$goto\"'></p>";
die();
}
$base64data = $sobretimbre->getElementsByTagNameNS('http://cfdi.service.ediwinws.edicom.com', 'getCfdiReturn')->item(0)->textContent;
$zipdata = base64_decode($base64data);
$zipfilename = tempnam(sys_get_temp_dir(), 'cfdi');
$zipfile = fopen($zipfilename,'w');
fwrite($zipfile, $zipdata);
fclose($zipfile);
$zip = new ZipArchive;
if ($zip->open($zipfilename) === TRUE) {
$timbrecfdi = $zip->getFromName("SIGN_XML_COMPROBANTE_3_0.xml");
$xmltimbre->loadXML($timbrecfdi) or die("\n\n\nXML no valido");
$zip->close();
} else {
die("\n\n\nError de zip\n$return");
}
$t = $xmltimbre->getElementsByTagNameNS('http://www.sat.gob.mx/TimbreFiscalDigital', 'TimbreFiscalDigital')->item(0);
$sellosat = $t->getAttribute('selloSAT');
$uuid = $t->getAttribute('UUID');
//echo "!!!".$uuid."!!!";
$fechatimbrado = $t->getAttribute('FechaTimbrado');
$certificadoSAT = $t->getAttribute('noCertificadoSAT');
$version = $t->getAttribute('version');
$sellocfd = $t->getAttribute('selloCFD');
$complemento = "||".$version."|".$uuid."|".$fechatimbrado."|".$sellocfd."|".$certificadoSAT."||";
$cfdi = $xmltimbre->saveXML();
unset($timbre, $xml, $sobretimbre, $xmltimbre, $t);
$sql5 = "UPDATE nomina SET selloSAT = '".$sellosat."', UUID = '".$uuid. "', fechatimbrado = '" . $fechatimbrado . "', certificadoSAT = '" . $certificadoSAT . "', version = '" . $version . "', selloCFD = '" . $sellocfd . "', cadena_complemento = '" . $complemento."' WHERE id = ".$_GET['id'];
$res5 = mysql_query($sql5) or die(mysql_error());
$dir = 'archivos1/';
//$titulo = 'nomina' . $row['numero'] . '.xml';
$titulo = 'nomina' . $id . '.xml';
file_put_contents($dir.$titulo, $cfdi);
echo $link = "Click aqui para descargar el archivo: <a href='" . $dir.$titulo . "'>" . $titulo . "</a>";
echo "<br/><p>";
$goto = "vista_previa.php?id=" . $id;
echo "<input name='submit' type='button' value='Continuar' onClick='javascript: window.location.href=\"$goto\"'></p>";
?>
Replace
$sqlFolios = "SELECT * FROM folios_asignados WHERE (id_empresa = ".$row['idEmpresa'].")";
With
$sqlFolios = "SELECT * FROM folios_asignados WHERE (id_empresa = '".$row['idEmpresa']."')";
You need to surround $row['idEmpresa'] with single quote marks.

Create multiple php commands (Prestashop)

I develop a module for a prestashop 1.5 to manage product subscriptions. I am looking to create x order based on what customer to select 3 months, 6 months or 12 months. I already made the logic to recover what was selected I just miss to create the x commands here is what I already did.
public function newBox($theCart, $referencesProducts, $subscribeMonth)
{
$nbMonth = preg_replace('~\D~', '', $subscribeMonth);
foreach ($referencesProducts as $referencesProduct) {
$ids_product[] = Db::getInstance()->getRow('SELECT id_product FROM ' . _DB_PREFIX_ . 'product WHERE reference =\''.$referencesProduct.'\'');
}
// Si le nbMonth est égale à 1 an alors on applique un resultat à 12 (mois)
if ($nbMonth == 1) {
$productSelected = array_slice($ids_product, 0, 12);
} else {
$productSelected = array_slice($ids_product, 0, $nbMonth);
}
// On créer les commandes
$order = new Order();
$order->id_customer = $theCart->id_customer;
$order->id_shop = $theCart->id_shop;
$order->id_currency = $theCart->id_currency;
$order->id_lang = $theCart->id_lang;
$order->id_address_invoice = $theCart->id_address_invoice;
$order->id_address_delivery = $theCart->id_address_delivery;
}
In my code I retrieve the list of the products that for each order, if subscription 3 months I recover a table of 3 products if subscription 6 months I recover an array of 6 products. So I have to integrate 1 product per order, how can I do that?
I find how to do it here code.
Thank you.
public function newBox($theCart, $referencesProducts, $subscribeMonth, $showDate)
{
$reference = Order::generateReference();
$nbMonth = preg_replace('~\D~', '', $subscribeMonth);
foreach ($referencesProducts as $referencesProduct) {
$ids_product[] = Db::getInstance()->getRow('SELECT id_product FROM ' . _DB_PREFIX_ . 'product WHERE reference =\'' . $referencesProduct . '\'');
}
// Si le nbMonth est égale à 1 an alors on applique un resultat à 12 (mois)
if ($nbMonth == 1) {
$productSelected = array_slice($ids_product, 0, 12);
} else {
$productSelected = array_slice($ids_product, 0, $nbMonth);
}
foreach ($productSelected as $products) {
$this->calculDate($showDate);
// On créer les commandes
$order = new Order();
$order->product_list = $products;
$order->id_customer = (int)$theCart->id_customer;
$order->id_address_invoice = (int)$theCart->id_address_invoice;
$order->id_address_delivery = (int)$theCart->id_address_delivery;
$order->id_currency = $theCart->id_currency;
$order->id_carrier = $theCart->id_carrier;
$order->id_lang = (int)$theCart->id_lang;
$order->id_cart = (int)$theCart->id;
$order->reference = $reference;
$order->id_shop = (int)$theCart->id_shop;
$order->id_shop_group = (int)$theCart->id_shop_group;
$order->current_state = 2;
$order->payment = "Unknown";
$order->module = "Unknown";
$order->secure_key = $theCart->secure_key;
$order->conversion_rate = 1;
$order->invoice_number = 0;
$order->delivery_number = 0;
$order->valid = 0;
$order->date_add = date('Y-m-d h:i:s');
$order->date_upd = date('Y-m-d h:i:s');
$order->recyclable = $theCart->recyclable;
$order->gift = (int)$theCart->gift;
$order->gift_message = $theCart->gift_message;
$order->mobile_theme = $theCart->mobile_theme;
$order->total_paid_real = 0;
$order->total_products = 0;
$order->total_products_wt = 0;
$order->total_discounts_tax_excl = 0;
$order->total_discounts_tax_incl = 0;
$order->total_discounts = 0;
$order->total_shipping_tax_excl = 0;
$order->total_shipping_tax_incl = 0;
$order->total_shipping = 0;
$order->total_wrapping_tax_excl = 0;
$order->total_wrapping_tax_incl = 0;
$order->total_wrapping = 0;
$order->total_paid_tax_excl = 0;
$order->total_paid_tax_incl = 0;
$order->total_paid = 0;
$order->invoice_date = '0000-00-00 00:00:00';
$order->delivery_date = '0000-00-00 00:00:00';
// Creating order
$result = $order->add();
if (!$result)
throw new PrestaShopException('Can\'t save Order');
}
}

Weird symbols before JSON in Android app from PHP server

I get this error when I try to parse JSON in Android app from PHP server.
This error I get:
05-26 14:38:44.963: D/TAG(31618): test u try
05-26 14:38:44.968: W/System.err(31618): org.json.JSONException: Value ?»??»? of type 05-26 14:38:44.963: D/TAG(31618): test u try
05-26 14:38:44.968: W/System.err(31618): org.json.JSONException: Value ?»??»? of type java.lang.String cannot be converted to JSONObject
Here is JSON which I get from PHP server, as you can see there are some weird ?»??»? characters before JSON.
Here is JSON:
?»??»?{
"horoscope":[
{
"name_sign":"Ovan",
"txt_hrs":"Neke promene koje ste ve\u0107 izvesno vreme izbegavali, danas dolaze na dnevni red. Mogu\u0107e je da \u0107ete imati priliku da promenite mesto stanovanja ili posao. Tako\u0111e, pred vama je jedno kra\u0107e putovanje koje nikako ne biste smeli da propustite. O\u010dekuje vas manji problem sa respiratornim sistemom. Prekontroli\u0161ite krvnu sliku."
},
{
"name_sign":"Bik",
"txt_hrs":"Pobolj\u0161anje u komunikaciji donosi pobolj\u0161anja na poslovnom planu. Veoma je mogu\u0107e da \u0107ete danas \u010duti neke pozitivne vesti vezane za napredovanje u karijeri. Emotivni odnosi se tako\u0111e pobolj\u0161avaju. Partner i vi kona\u010dno pronalazite zajedni\u010dki jezik."
},
{
"name_sign":"Blizanci",
"txt_hrs":"Mogu\u0107e je da danas budete nervozniji nego ina\u010de i pomalo deprimirani, a sve kao rezultat odvojenosti od voljenog bi\u0107a. Ne bi bilo lo\u0161e da se neko vreme posvetite poslovnim projektima, naro\u010dito onima koji zahtevaju izvesnu dozu kreativnosti. Bi\u0107ete zadovoljni postignutim rezultatima, a i vreme \u0107e vam znatno br\u017ee prote\u0107i."
},
{
"name_sign":"Rak",
"txt_hrs":"Iznenadna poseta bliske osobe koja je zapala u izvesne probleme, menja vam uobi\u010dajenu rutinu i ostavlja vas zate\u010denim. Ne mo\u017eete da prihvatite da se ovako ne\u0161to de\u0161ava va\u0161im dragim ljudima. Pa ipak, najbitnije je da joj ne sudite i da pru\u017eite punu emotivnu podr\u0161ku. Tako\u0111e, o\u010dekuju vas povoljne vesti iz inostranstva."
},
{
"name_sign":"Lav",
"txt_hrs":"Neo\u010dekivani susret sa voljenim bi\u0107em ili jednom mla\u0111om osobom ostavlja vas u prijatnom raspolo\u017eenju i veri u bolju budu\u0107nost. Nastojte da vi\u0161e vremena provedete sa njom. Danas biste tako\u0111e mogli da budete u prilici da po\u0161aljete mnogo pisama, mejlova ili obavite mnogo telefonskih razgovora. O\u010dekuju vas dobre vesti od jednog \u010dlana porodice."
},
{
"name_sign":"Devica",
"txt_hrs":"Neke stvari koje su van va\u0161e kontrole \u010dine vas frustriranim i punim negativne energije. Da biste se re\u0161ili toga, posvetite se nekim rutinskim poslovima koji zamaraju telo, a odmaraju duh. Ne bi bilo lo\u0161e da se odlu\u010dite za spremanje doma ili oku\u0107nice. Uve\u010de na\u0111ite vremena za prijatelje i \u010dlanove porodice."
},
{
"name_sign":"Vaga",
"txt_hrs":"Nesporazumi u komunikaciji mogli bi da vas nepotrebno zavade sa dragim ljudima. Tako\u0111e, ne dozvolite sebi da se danas konfrontirate sa nadre\u0111enima u poslovnom okru\u017eenju. Najbolje bi bilo da se danas dr\u017eite po strani kada su razgovori u pitanju i da nikako ne iznosite va\u0161e mi\u0161ljenje. Postoji opasnost da budete pogre\u0161no shva\u0107eni."
},
{
"name_sign":"\u0160korpija",
"txt_hrs":"Nov\u010dani dugovi sa po\u010detka nedelje danas dolaze na naplatu. Ovo u vama izaziva nervozu i prave male napade panike, ali najbitnije je da se saberete i smireno razmotrite novonastalu situaciju. Obratite se svima u koje imate poverenja za savet ili \u010dak pozajmicu. Neka vam ovo bude nauk da u budu\u0107e pa\u017eljivije planirate tro\u0161kove."
},
{
"name_sign":"Strelac",
"txt_hrs":"Neke sre\u0107ne okolnosti u \u017eivotu jednog va\u0161eg bliskog prijatelja u\u010dini\u0107e da se i vi osetite sre\u0107nim i ponosnim. Ovoj situaciji je prethodilo mnogo truda i napornog rada. Svakako se potrudite da to zajedno proslavite. Na poslovnom planu zadr\u017eite optimizam, a svakako i veru u vlastite sposobnosti. Uspeh ni u va\u0161em slu\u010daju ne\u0107e izostati."
},
{
"name_sign":"Jarac",
"txt_hrs":"Ovaj dan donosi preokret na polju karijere. Ve\u0107 dugo ste nazadovoljni aktuelnom situacijom i svesni ste da je do\u0161lo vreme za nove po\u010detke. Mogu\u0107e je da \u0107ete u potpunosti promeniti profesiju. Ona najverovatnije uklju\u010duje kori\u0161\u0107enje novih tehnologija. Potrudite se da na vreme proverite da li posedujete odgovaraju\u0107e ve\u0161tine i kvalifikacije za takvu vrstu posla."
}
]
}
PHP Code:
<?php
include('../lib/horoskopiusphpsdk.php');
$horoskopius = new HoroskopiusSDK();
$horoskopius->setPrivateKey("i1pOy/g5wF2BmMTKVxHXsSQO1V0=");
$horoskopius->setPublicKey("NjFlMjNkNzJjNmY0NDE1MDBkNDU3NmRlZDdjOWMxOTI0YjhlYjE0OQ==");
$horoskopius->setHoroscope(1);
$horoskopius->setCategory(1);
$horoskopius->setHoroscopeType(1);
$horoskopius->setResponseType("json");
$horoskopius->setAlphabet(1); //nova funkcija 1 = latinica, 2 = ćirilica
$horoskopius->getResponse();
?>
PHP lib class
<?php
if (!function_exists('curl_init')) {
throw new HoroskopiusAPIException('Horoskopius SDK zahteva CURL PHP ekstenziju.');
}
if (!function_exists('json_decode')) {
throw new HoroskopiusAPIException('Horoskopius SDK zahteva JSON PHP ekstenziju.');
}
define('HOR_PATH_BASE', dirname(__FILE__) );
define( 'DRS', DIRECTORY_SEPARATOR );
class HoroskopiusAPIException extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
class HoroskopiusSDK {
private $public_key;
private $private_key;
private $horoscope;
private $horoscope_type;
private $category;
private $cache;
private $response_type;
private $signature;
/* Headlines */
private $headline_horoscope;
private $headline_category;
private $headline_type;
private $date_horoskop;
private $speedup;
private $latin;
public function __construct() {
$this->response_type = 'xml';
$this->horoscope = 1;
$this->category = 1;
$this->horoscope_type = 1;
$this->cache = 1;
$this->speedup = 1;
$this->latin = 1;
}
public function setAlphabet($i) {
$this->latin = ($i > 0 && $i <= 2) ? $i : $this->latin;
}
private function generateSignature($k) {
$sig = base64_encode(hash_hmac('sha1', $k, true));
return $sig;
}
public function setResponseType($s) {
if ($s == NULL) :
$this->response_type = 'xml';
else:
$this->response_type = $s;
endif;
}
public function setHoroscope($i) {
$this->horoscope = ($i > 0 && $i <= 2) ? $i : $this->horoscope;
if ($this->horoscope == 1) :
$this->headline_horoscope = 'Horoskop';
else :
$this->headline_horoscope = 'Kineski horoskop';
endif;
}
public function setCache($i) {
$this->cache = ($i > 0 && $i <= 2) ? $i : $this->cache;
}
public function setSpeedUp($i) {
$this->speedup = ($i > 0 && $i <= 2) ? $i : $this->speedup;
}
public function setCategory($i) {
$this->category = ($i > 0 && $i <= 3) ? $i : $this->category;
if ($this->category == 1 && $this->horoscope == 1) :
$this->headline_category = '';
elseif($this->category == 2 && $this->horoscope == 1) :
$this->headline_category = 'Ljubavni ';
elseif($this->category == 3 && $this->horoscope == 1) :
$this->headline_category = 'Poslovni ';
else :
$this->headline_category = null;
endif;
}
public function setHoroscopeType($i) {
$this->horoscope_type = ($i > 0 && $i <= 3) ? $i : $this->horoscope_type;
if ($this->horoscope_type == 1) :
$this->headline_type = 'Dnevni ';
elseif($this->horoscope_type == 2) :
$this->headline_type = 'Nedeljni ';
elseif($this->horoscope_type == 3) :
$this->headline_type = 'Mesečni ';
else :
$this->headline_type = null;
endif;
}
public function setPrivateKey($k) {
$this->private_key = $k;
}
public function setPublicKey($k) {
$this->public_key = $k;
}
public function getResponse() {
switch ($this->response_type) :
case 'xml':
$this->returnXML();
break;
case 'json':
/*$this->returnJSON();*/
$this->encodeJSON();
break;
endswitch;
}
private function setCurlResponse() {
$this->signature = $this->generateSignature($this->private_key);
$url = "http://dev.horoskopius.com/service/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POSTFIELDS, "type=$this->response_type&horoscope=$this->horoscope&category=$this->category&horoscope_type=$this->horoscope_type&sig=" . urlencode($this->signature) . "&auth=" . urlencode($this->public_key) . "&cache=" . $this->cache ."");
curl_setopt($ch, CURLOPT_USERAGENT, 'Horoskopius');
$result = curl_exec($ch);
return $result;
}
private function returnXML() {
$cachefile = HOR_PATH_BASE . DRS . 'cachebase' . DRS . $this->response_type . $this->category . $this->horoscope . $this->horoscope_type . '.htm';
$cachetime = 180*60;
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile)) && $this->speedup == 1) :
require($cachefile);
echo '<!-- speed up horoskopius -->';
else:
$response = $this->setCurlResponse();
$xml = new SimpleXmlElement($response, LIBXML_NOCDATA);
$cnt = count($xml->{"horoscope"});
$content = '<div id="horoskopius">'.
'<h2>' . $this->latin2cyrillic($this->headline_type . $this->headline_category . $this->headline_horoscope) . '</h2>'.
'<span class="horoskopius-date"></span><ul>';
for($i=0; $i<$cnt; $i++) :
$content.= '<li><span class="sign-container hor-' . strtolower(str_replace("Š", "s", $xml->{"horoscope"}[$i]->{"sign"})) . '"></span><h3>' . $this->latin2cyrillic($xml->{"horoscope"}[$i]->{"sign"}) . '</h3> ' . $this->latin2cyrillic($xml->{"horoscope"}[$i]->{"horoscopetxt"}) . '</li>';
endfor;
$content .= '<li class="horoskopius-link">' . $this->latin2cyrillic('Horoskop obezbedio - Astro portal').' Horoskopius</li>';
$content .= '</ul></div>';
echo $content;
$fp = fopen($cachefile, 'w');
fwrite($fp, $content);
fclose($fp);
endif;
}
private function encodeJSON() {
$cachefile = HOR_PATH_BASE . DRS . 'cachebase' . DRS . $this->response_type . $this->category . $this->horoscope . $this->horoscope_type . '.htm';
$cachetime = 180*60;
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile)) && $this->speedup == 1) {
// get data from cache
$response = file_get_contents($cachefile);
// output data
echo $response;
} else {
// collect new data
$response = $this->setCurlResponse();
// cache data
$fp = fopen($cachefile, 'w');
fwrite($fp, $response);
fclose($fp);
// output data
echo $response;
}
}
private function returnJSON() {
$cachefile = HOR_PATH_BASE . DRS . 'cachebase' . DRS . $this->response_type . $this->category . $this->horoscope . $this->horoscope_type . '.htm';
$cachetime = 180*60;
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile)) && $this->speedup == 1) :
require($cachefile);
echo '<!-- speed up horoskopius -->';
else:
$response = $this->setCurlResponse();
$json = json_decode($response);
$content = '<div id="horoskopius">'.
'<h2>' . $this->latin2cyrillic($this->headline_type . $this->headline_category . $this->headline_horoscope) . '</h2>'.
'<span class="horoskopius-date"></span><ul>';
$cnt = count($json->{"horoscope"});
for($i=0; $i<$cnt; $i++) :
$content .= '<li><span class="sign-container hor-' . strtolower(str_replace("Š", "s", $json->{"horoscope"}[$i]->{"name_sign"})) . '"></span><h3>' . $this->latin2cyrillic($json->{"horoscope"}[$i]->{"name_sign"}) . '</h3> ' . $this->latin2cyrillic($json->{"horoscope"}[$i]->{"txt_hrs"}) . '</li>';
endfor;
$content .= '<li class="horoskopius-link"> ' . $this->latin2cyrillic('Horoskop obezbedio - Astro portal') . ' Horoskopius</li>';
$content .= '</ul></div>';
echo $content;
$fp = fopen($cachefile, 'w');
fwrite($fp, $content);
fclose($fp);
endif;
}
private function latin2cyrillic($text) {
$tr = array(
"A"=>"А",
"B"=>"Б",
"C"=>"Ц",
"Č"=>"Ч",
"D"=>"Д",
"Đ"=>"Ђ",
"E"=>"Е",
"F"=>"Ф",
"G"=>"Г",
"H"=>"Х",
"I"=>"И",
"J"=>"Ј",
"K"=>"К",
"L"=>"Л",
"M"=>"М",
"N"=>"Н",
"O"=>"О",
"P"=>"П",
"R"=>"Р",
"S"=>"С",
"Š"=>"Ш",
"T"=>"Т",
"U"=>"У",
"V"=>"В",
"Z"=>"З",
"Ž"=>"Ж",
"Ć"=>"Ћ",
"a"=>"а",
"b"=>"б",
"c"=>"ц",
"č"=>"ч",
"ć"=>"ћ",
"d"=>"д",
"đ"=>"ђ",
"e"=>"е",
"f"=>"ф",
"g"=>"г",
"h"=>"х",
"i"=>"и",
"j"=>"ј",
"k"=>"к",
"l"=>"л",
"m"=>"м",
"n"=>"н",
"o"=>"о",
"p"=>"п",
"r"=>"р",
"s"=>"с",
"š"=>"ш",
"t"=>"т",
"u"=>"у",
"v"=>"в",
"z"=>"з",
"ž"=>"ж",
"Lj"=>"Љ",
"Nj"=>"Њ",
"Dž"=>"Џ",
"lj"=>"љ",
"nj"=>"њ",
"dž"=>"џ"
);
if ($this->latin == 2) :
return strtr($text,$tr);
else :
return $text;
endif;
}
}?>
This could be a problem with byte order mark in json outputs. I`m not familiar with android, but make sure the app handles json BOM in a proper way ( as whitespaces ). If so, check your php files for correct utf8 encoding. In the editor i use for php, i save files as utf8 encoded without BOM.
The problem was with empty lines before and after PHP code.

PhpExcel SUM() returning 0

So as said in the title, the SUM() function I use in my PHP always displays a "0" in the generated document.
What is weird is that when I do the same formula directly in the doc, by selecting the cell etc.., the result is good :/
Here is the code :
public function generateDocument($name, $description, $params, $criteres, $options) {
// création du doc au format xsl
$doc = new \PHPExcel();
$doc->getProperties()->setCreator(UASG_NAME)
->setTitle($name)
->setDescription($description);
$doc->setActiveSheetIndex(0);
$worksheet = $doc->getActiveSheet();
// création du nom de l'onglet pour les datas
$worksheet->setTitle($this->createSheetTitle($name));
$dataService = new DataService($this->pdo, $this->context, $this->logger);
$table=$dataService->search($params, $criteres);
$this->startTimer("GENEREDATAS");
$headRow=null;$totalRow=null;
$this->currencyColumns = array();
$lineNumber = 1;
// ajout du titre en haut du fichier
if(isset($options->heading) && $options->heading!=""){
$worksheet->mergeCells('A1:Z2');
$worksheet->setCellValue('A1', $options->heading);
$worksheet->getStyle('A1')->getFont()->setSize(13);
$worksheet->getStyle('A1')->getFont()->setBold(true);
$previousLineNumber=4;
}else{
$previousLineNumber=0;
}
foreach ($table['rows'] as $rowindex => $row) {
$nbColumn=count($row['cells']);
foreach ($row['cells'] as $column => $cell) {
// header
if ($rowindex == 0) {
$title = $table['headers'][$column];
$this->setCellValue($worksheet, $column, $previousLineNumber + 1, $title);
$headRow = $previousLineNumber + 1;
}
// cellule
if ($row['level'] == 0) {
if ($column == 0) {
$lineNumber++;
}
$columnCell=$column;
$this->setCellValue($worksheet, $columnCell, $lineNumber + $previousLineNumber, $cell);
}
$worksheet->getColumnDimensionByColumn($column)->setAutoSize(true);
}
}
if(isset($options->totalPrice) && $options->totalPrice == 1){
$borderStyle= array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THICK
)
)
);
$worksheet->getStyleByColumnAndRow($nbColumn-1, $lineNumber+$previousLineNumber+2)->applyFromArray($borderStyle);
$worksheet->setCellValueByColumnAndRow($nbColumn-1, $lineNumber+$previousLineNumber+2, '=SUM(E2:E100)');
// '=SUM(F'.($previousLineNumber+2).':F'.($lineNumber+2).')');
}
if (isset($nbColumn)) {
$lastColumn = $nbColumn - 1;
// mise en forme des titres
$range = \PHPExcel_Cell::stringFromColumnIndex(0) . $headRow . ':' . \PHPExcel_Cell::stringFromColumnIndex($lastColumn) . $headRow;
$worksheet->getStyle($range)->applyFromArray($this->getHeadStyle());
$range = \PHPExcel_Cell::stringFromColumnIndex(0) . ($previousLineNumber) . ':' . \PHPExcel_Cell::stringFromColumnIndex($nbColumn) . ($lineNumber + $previousLineNumber + 1);
$worksheet->getStyle($range)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
// mise en forme des colonnes des devises
if (count($this->currencyColumns)>0) {
foreach($this->currencyColumns as $column) {
$range = \PHPExcel_Cell::stringFromColumnIndex($column) . ($previousLineNumber) . ':' . \PHPExcel_Cell::stringFromColumnIndex($column) . ($lineNumber + $previousLineNumber + 1);
$worksheet->getStyle($range)->getNumberFormat()->setFormatCode('#,##0.00_-[$' . $this->currencySymbol . ' ]');
}
}
unset($nbColumn);
}
$this->stopTimer("GENEREDATAS");
$doc->setActiveSheetIndex(0);
$this->startTimer("WRITE");
$writer = \PHPExcel_IOFactory::createWriter($doc, 'Excel2007');
//$writer->setPreCalculateFormulas(false);
$writer->save('php://output');
$this->stopTimer("WRITE");
}
I thought it might be a problem about languages. Because I'm opening the doc in an English Ubuntu so that may be the problem, but I don't know how to pass through that easily..
If someone could help that would be awesome.
You need adjust this
$writer->setPreCalculateFormulas(true);

Draw image with zendPDF

Im using the PDF parser that comes with zend framework. Im trying to trying draw an image, but get an error.
function addReklam($reklamblad) //picture.png
{
// kolla hur många sidor som skapats och lägg till en sista reklamsida:
//Öppna fil här, lägg till den i PDF
$fish = 0;
if($this->drawed_lines<52)
{
$this->active_page = $this->pdf->pages[2];
$fish = 1;
}
elseif($this->drawed_lines<92)
{
$this->active_page = $this->pdf->pages[3];
$fish = 2;
}
elseif($this->drawed_lines<132)
{
$this->active_page = $this->pdf->pages[4];
$fish = 3;
}
else
{
$this->active_page = $this->pdf->pages[5];
$fish = 4;
}
//$this->active_page = $this->pdf->pages[5]; // sida 5 är reklamsidan
$image = $this->imageWidthPath($reklamblad);
$this->active_page->drawImage($image, $left, $bottom, $right, $top);
}
I get this message:
Fatal error: Call to undefined method fakturapdf::imageWidthPath() in /data/web/script/pdffaktura/testpdf-txt.php on line 681
EDIT:
I've tried like this now:
function addReklam($reklamblad)
{
// kolla hur många sidor som skapats och lägg till en sista reklamsida:
//Öppna fil här, lägg till den i PDF
$fish = 0;
if($this->drawed_lines<52)
{
$this->active_page = $this->pdf->pages[2];
$fish = 1;
}
elseif($this->drawed_lines<92)
{
$this->active_page = $this->pdf->pages[3];
$fish = 2;
}
elseif($this->drawed_lines<132)
{
$this->active_page = $this->pdf->pages[4];
$fish = 3;
}
else
{
$this->active_page = $this->pdf->pages[5];
$fish = 4;
}
//$this->active_page = $this->pdf->pages[5]; // sida 5 är reklamsidan
$image = Zend_Pdf_Image::imageWithPath($reklamblad);
$this->active_page->drawImage($image, 400, 400, 400, 400);
}
This seems to work fine, I'll get no errors. But is this the correct way to use it? Nothing is printed to the PDF.
Yes it's correct. It's Zend_Pdf_Image::imageWithPath and not $this->imageWidthPath().
It's a static method.
If it helps you, I found it.

Resources