Curl return 404, but 200 with Postman - php
I have a curl call to API on localhost. The call worked before, but now I get a 404 error. Now, if I run the same query in Postman it works fine all time. I can't understand why.
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json; charset=utf-8;'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //POST
curl_setopt($ch, CURLOPT_URL, $url_base.$url.$token);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$curl_log = fopen("curl.txt", 'a'); // open file for READ and write
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_STDERR, $curl_log);
if(!empty($data)) {
if($method == "POST" || $method == "PUT") {
curl_setopt($ch, CURLOPT_POSTFIELDS,$data); //(json)
}
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$aux = curl_exec($ch);
rewind($curl_log);
$output = fread($curl_log, 2048);
echo "<pre>" . print_r($output, 1) . "</pre>";
fclose($curl_log);
if (curl_errno($ch)) {
$error_msg = curl_error($ch); //404
}
Sorry, but the URL contain a private token
Postman Request:
curl --location --request POST 'https://PRIVATEURL' \
--header 'Content-Type: application/json' \
--data-raw '{"data":{"id":null,"name":"Solo","supplierId":null,"rooms":3,"livingRoom":null,"bathrooms":2,"toilets":1,"totalBeds":6,"supportedLosRates":false,"space":"190","spaceUnit":"SQ_M","persons":6,"childs":null,"latitude":48.8678000000000025693225325085222721099853515625,"longitude":2.35024999999999995026200849679298698902130126953125,"altId":"50","currency":"EUR","location":{"postalCode":"75002","country":"FR","region":"Paris","city":"Paris","street":"16-28 Rue du Caire","zipCode9":null},"propertyType":"PCT3","attributesWithQuantity":[],"notes":{"description":{"texts":[{"language":"ES","value":"Con el Palacio del El\u00edseo como vecino, ad\u00e9ntrese en el lujo y la sofisticaci\u00f3n franceses en el coraz\u00f3n del 8e Arrondissement en Par\u00eds. Ubicado en un edificio aristocr\u00e1tico de 1858, este apartamento de Haussmann representa una pieza de la historia representativa del \"arte de vivir\" \u00e0 la Fran\u00e7aise en el siglo XIX. Art de Vivre \u00c9lys\u00e9e ofrece un sentimiento de castillo para los viajeros epic\u00fareos que disfrutan de grandes espacios interiores mientras est\u00e1n rodeados de las mejores cosas de la vida, tanto en casa como a la puerta.Este alquiler de vacaciones exhibe antig\u00fcedades que han sido cuidadosamente coleccionadas, yuxtapuestas con mobiliario contempor\u00e1neo y equipamiento actualizado. Salga al balc\u00f3n de hierro forjado de treinta pies de largo y contemple la escena del tr\u00e1fico y los peatones de abajo. Los extras de este apartamento incluyen conexi\u00f3n Wi-Fi, una cafetera espresso, TV v\u00eda sat\u00e9lite y un sistema de sonido Sonos.Con su decoraci\u00f3n grandiosa, su serie de recepciones espaciosas con techos altos y 15 ventanas del piso al techo disfrutan de la secuencia de patrones de claroscuros moldeados por la luz cambiante del d\u00eda. Admire las cornisas finamente trabajadas, las molduras talladas, los frisos delicadamente esculpidos, los pisos de parquet de espiga de roble, las chimeneas de m\u00e1rmol, el bronce y los candelabros de cristal. Disfrute de una comida suculenta en el comedor formal y la cocina bien equipada con vistas a un patio con establos antiguos."},{"language":"EN","value":"With the Elys\u00e9e Palace as a neighbor, immerse yourself in French luxury and sophistication in the heart of the 8th Arrondissement in Paris. Housed in an aristocratic building from 1858, this Haussmann apartment represents a piece of history representative of the \"art of living\" \u00e0 la Fran\u00e7aise in the 19th century. Art de Vivre \u00c9lys\u00e9e offers a castle feeling for epicurean travelers who enjoy large indoor spaces while surrounded by the best things in life, both at home and at the door. This vacation rental exhibits antiques that have been carefully collected, juxtaposed with contemporary furniture and updated equipment. Exit to the thirty-foot-long wrought-iron balcony and watch the traffic scene and the pedestrians below. Extras in this apartment include Wi-Fi, an espresso machine, satellite TV and a Sonos sound system. With its grandiose d\u00e9cor, its series of spacious receptions with high ceilings and 15 floor-to-ceiling windows enjoy the sequence of chiaroscuro patterns molded by the changing light of the day. Admire the finely worked cornices, carved moldings, delicately sculpted friezes, oak herringbone floors, marble fireplaces, bronze and crystal chandeliers. Enjoy a succulent meal in the formal dining room and the well-equipped kitchen overlooking a courtyard with old stables. "},{"language":"FR","value":"Avec l'\''Elys\u00e9e en tant que voisin, plongez dans le luxe et la sophistication fran\u00e7aise au c\u0153ur du 8\u00e8me arrondissement de Paris. Install\u00e9 dans un b\u00e2timent aristocratique de 1858, cet appartement haussmannien repr\u00e9sente une pi\u00e8ce d'\''histoire repr\u00e9sentative de \u00abl'\''art de vivre\u00bb \u00e0 la Fran\u00e7aise au XIXe si\u00e8cle. Art de Vivre \u00c9lys\u00e9e offre un sentiment de ch\u00e2teau pour les voyageurs \u00e9picuriens qui aiment les grands espaces int\u00e9rieurs tout en \u00e9tant entour\u00e9 par les choses de la vie, \u00e0 la fois \u00e0 la maison et \u00e0 la porte. Cette location de vacances pr\u00e9sente des antiquit\u00e9s qui ont \u00e9t\u00e9 soigneusement collect\u00e9es, juxtapos\u00e9es avec des meubles contemporains et des \u00e9quipements mis \u00e0 jour. Sortez sur le balcon en fer forg\u00e9 de trente pieds de long et observez la circulation et les pi\u00e9tons en contrebas. Les extras dans cet appartement comprennent une connexion Wi-Fi, une machine \u00e0 expresso, la t\u00e9l\u00e9vision par satellite et un syst\u00e8me de son Sonos. Avec son d\u00e9cor grandiose, sa s\u00e9rie d'\''accueil avec de hauts plafonds et des fen\u00eatres 15 du sol au plafond b\u00e9n\u00e9ficient des motifs s\u00e9quence de clair-obscur en forme par la lumi\u00e8re du jour changeant. Admirez les corniches finement travaill\u00e9es, les moulures sculpt\u00e9es, les frises d\u00e9licatement sculpt\u00e9es, les planchers en ch\u00eane \u00e0 chevrons, les chemin\u00e9es en marbre, les lustres en bronze et en cristal. Profitez d'\''un succulent repas dans la salle \u00e0 manger formelle et la cuisine bien \u00e9quip\u00e9e donnant sur une cour avec de vieilles \u00e9curies. "},{"language":"IT","value":"Con l'\''Elys\u00e9e Palace come vicino di casa, immergiti nel lusso francese e nella raffinatezza nel cuore dell'\''8 \u00b0 arrondissement a Parigi. Ospitato in un edificio aristocratico dal 1858, questo appartamento Haussmann rappresenta un pezzo di storia rappresentante dell '\''\"arte di vivere\" \u00e0 la Fran\u00e7aise nel 19 \u00b0 secolo. L'\''Art de Vivre \u00c9lys\u00e9e offre un'\''atmosfera da castello per viaggiatori epicurei che amano i grandi spazi interni mentre sono circondati dalle cose migliori della vita, sia a casa che alla porta. Questa casa vacanze espone oggetti d'\''antiquariato raccolti con cura, giustapposti a mobili contemporanei e attrezzature aggiornate. Esci sul balcone di ferro battuto lungo trenta metri e osserva la scena del traffico e i pedoni sottostanti. Gli extra di questo appartamento includono la connessione Wi-Fi, una macchina per caff\u00e8 espresso, una TV satellitare e un sistema audio Sonos. Con il suo arredamento grandioso, la sua serie di ampi ricevimenti con soffitti alti e 15 finestre dal pavimento al soffitto godono della sequenza di modelli in chiaroscuro modellati dalla luce mutevole del giorno. Ammira le cornici finemente lavorate, le modanature scolpite, i fregi delicatamente scolpiti, i pavimenti in parquet di quercia a spina di pesce, i caminetti in marmo, i lampadari in bronzo e cristallo. Goditi un pasto succulento nella sala da pranzo formale e nella cucina ben attrezzata che si affaccia su un cortile con vecchie stalle. "},{"language":"PT","value":"Com o Elys\u00e9e Palace como vizinho, mergulhe no luxo franc\u00eas e na sofistica\u00e7\u00e3o no cora\u00e7\u00e3o do 8\u00ba Arrondissement, em Paris. Abrigado num edif\u00edcio aristocr\u00e1tico de 1858, este apartamento Haussmann representa uma hist\u00f3ria hist\u00f3rica representativa da \"arte de viver\" \u00e0 la Fran\u00e7aise no s\u00e9culo XIX. Art de Vivre \u00c9lys\u00e9e oferece um sentimento de castelo para os viajantes epic\u00faricos que desfrutam de grandes espa\u00e7os interiores, cercados pelas melhores coisas da vida, tanto em casa quanto na porta. Este aluguer de f\u00e9rias exibe antiguidades cuidadosamente coletadas, justapostas com m\u00f3veis contempor\u00e2neos e equipamentos atualizados. Saia da bala de ferro forjado de trinta metros de comprimento e assista a cena do tr\u00e2nsito e os pedestres abaixo. Os extras deste apartamento incluem Wi-Fi, m\u00e1quina de caf\u00e9 expresso, TV via sat\u00e9lite e sistema de som Sonos. Com sua decora\u00e7\u00e3o grandiosa, sua s\u00e9rie de recep\u00e7\u00f5es espa\u00e7osas com tectos altos e 15 janelas do ch\u00e3o ao teto desfrutam da sequ\u00eancia de padr\u00f5es de claroscuro moldados pela luz passageira do dia. Admire as cornijas finamente trabalhadas, molduras esculpidas, frisos delicadamente esculpidos, pisos de madeira de carvalho, lareiras de m\u00e1rmore, lustres de bronze e de cristal. Desfrute de uma refei\u00e7\u00e3o suculenta na sala de jantar formal e da cozinha bem equipada com vista para um p\u00e1tio com est\u00e1bulos antigos. "}]},"houseRules":{"texts":[]}},"bedroomConfiguration":null,"policy":{"internetPolicy":{"accessInternet":false,"kindOfInternet":null,"availableInternet":null},"parkingPolicy":{"accessParking":false,"locatedParking":null,"privateParking":false,"necessaryReservationParking":null},"petPolicy":{"allowedPets":"NotAllowed","chargePets":null},"childrenAllowed":false,"smokingAllowed":false},"checkInTime":"07:00:00","checkInToTime":null,"checkOutTime":"15:00:00"}}'
Output file 'curl.txt':
Trying PRIVATEIP...
TCP_NODELAY set
Connected to PRIVATEURL port 443 (#0)
ALPN, offering http/1.1
Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:#STRENGTH
successfully set certificate verify locations:
CAfile: C:\mamp\cacert.pem
CApath: none
SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
ALPN, server accepted to use http/1.1
Server certificate:
subject: OU=Domain Control Validated; CN=*.PRIVATESERVER
start date: Nov 22 16:32:04 2018 GMT
expire date: Jan 13 14:19:55 2021 GMT
subjectAltName: host "PRIVATESERVER" matched cert's "*.PRIVATESERVER"
issuer: C=BE; O=GlobalSign nv-sa; CN=AlphaSSL CA - SHA256 - G2
SSL certificate verify ok.
POST /xml/services/rest/supplierapi/PRIVATEURL HTTP/1.1
Host: PRIVATEURL
Accept: /
Content-type: application/json; charset=utf-8;
Content-Length: 1157
Expect: 100-continue
< HTTP/1.1 100 Continue
We are completely uploaded and fine
The requested URL returned error: 404
stopped the pause stream!
Closing connection 0
Related
Adding insert query in symfony migration file:error
I need to insert static data in DATABASE during migration. so in my migration file I am adding one insert query but this is unfortunately giving error. same sql query running properly in mysql console. $this->addSql('insert into `Translations` values('fr', '{ "footer_header": "Contactez-nous", "footer_address": "Tour Ariane 92088 La Défense", "footer_phone": "+33(1) 42 74 83 02", "footer_email": "marsh#marsh.com", "footer_website": "www.marsh.com", "footer_cookies": "Politique relative aux cookie", "footer_confidential": "Politique de confidentialité", "footer_utilise": "Conditions d’utilisation", "footer_link_tou": "https://www.marsh.com/fr/fr/terms-of-use.html", "footer_link_privacy": "https://www.marsh.com/fr/fr/privacy-notice.html", "footer_link_cookies": "https://www.marsh.com/fr/fr/cookie-notice.html", "marketing_contact": "Contact", "marketing_address": "Tour Ariane 92088 La Défense", "marketing_phone": "+33(1) 42 74 83 02", "marketing_email": "marsh#marsh.com", "price_lab": "Compte tenu des informations complétées précemment, votre prime s''élève à", "price_lab1": "HT", "price_lab2": "Taxes", "price_lab3": "TTC", "price_lab4": "Frais de gestion", "price_lab5": "Montant total de votre prime", "signature_heading": "Veuillez remplir les informations ci-dessous afin de signer électroniquement votre document :", "signature_name1_lab": "<div>Prénom</div>", "signature_name1": "Prénom", "signature_name2_lab": "<div>Nom</div>", "signature_name2": "Nom", "signature_phone_lab": "<div>Numéro de téléphone</div>", "signature_phone": "Format attendu : +33658968956", "signature_otp": "Nous vous avons envoyé votre code, merci de le renseigner ci-dessous.", "payment_gateway": "Pour vous permettre de procéder au règlement en ligne par carte bancaire de votre cotisation d’assurance en toute sérénité, MARSH a choisi la solution proposée par son partenaire bancaire : la Société Générale. Le paiement s’effectuant sur un serveur totalement sécurisé, aucune information ne transite par notre site https://connexion.marsh.com. Les échanges se déroulant en mode SSL (Secure Sockets Layer), norme de sécurité de transfert, l’ensemble des données sont cryptées afin d’empêcher leur lecture ou leur interception par des tiers. Ce protocole permet d’établir une connexion sécurisée sur Internet, afin d’exclure toute fraude. Le cadenas placé en barre d’adresse de votre écran témoigne de la sécurisation de la connexion ».", "payment_button": "Traiter le paiement", "final_page": "Votre demande est bien enregistrée. Nos équipes vont étudier votre dossier et reviendront vers vous par email rapidement. Si vous avez des questions, nous vous invitons à adresser un email à ", "final_file_name": "Votre document signé", "zipFile_Name": "Fichiers attachés" }')'); I am getting below error while executing.
The problem is because of the ', you need to escape it like that : $this->addSql('insert into `Translations` values(\'fr\', \'{ "footer_header": "Contactez-nous", "footer_address": "Tour Ariane 92088 La Défense", "footer_phone": "+33(1) 42 74 83 02", "footer_email": "marsh#marsh.com", "footer_website": "www.marsh.com", "footer_cookies": "Politique relative aux cookie", "footer_confidential": "Politique de confidentialité", "footer_utilise": "Conditions d’utilisation", "footer_link_tou": "https://www.marsh.com/fr/fr/terms-of-use.html", "footer_link_privacy": "https://www.marsh.com/fr/fr/privacy-notice.html", "footer_link_cookies": "https://www.marsh.com/fr/fr/cookie-notice.html", "marketing_contact": "Contact", "marketing_address": "Tour Ariane 92088 La Défense", "marketing_phone": "+33(1) 42 74 83 02", "marketing_email": "marsh#marsh.com", "price_lab": "Compte tenu des informations complétées précemment, votre prime s élève à", "price_lab1": "HT", "price_lab2": "Taxes", "price_lab3": "TTC", "price_lab4": "Frais de gestion", "price_lab5": "Montant total de votre prime", "signature_heading": "Veuillez remplir les informations ci-dessous afin de signer électroniquement votre document :", "signature_name1_lab": "<div>Prénom</div>", "signature_name1": "Prénom", "signature_name2_lab": "<div>Nom</div>", "signature_name2": "Nom", "signature_phone_lab": "<div>Numéro de téléphone</div>", "signature_phone": "Format attendu : +33658968956", "signature_otp": "Nous vous avons envoyé votre code, merci de le renseigner ci-dessous.", "payment_gateway": "Pour vous permettre de procéder au règlement en ligne par carte bancaire de votre cotisation d’assurance en toute sérénité, MARSH a choisi la solution proposée par son partenaire bancaire : la Société Générale. Le paiement s’effectuant sur un serveur totalement sécurisé, aucune information ne transite par notre site https://connexion.marsh.com. Les échanges se déroulant en mode SSL (Secure Sockets Layer), norme de sécurité de transfert, l’ensemble des données sont cryptées afin d’empêcher leur lecture ou leur interception par des tiers. Ce protocole permet d’établir une connexion sécurisée sur Internet, afin d’exclure toute fraude. Le cadenas placé en barre d’adresse de votre écran témoigne de la sécurisation de la connexion ».", "payment_button": "Traiter le paiement", "final_page": "Votre demande est bien enregistrée. Nos équipes vont étudier votre dossier et reviendront vers vous par email rapidement. Si vous avez des questions, nous vous invitons à adresser un email à ", "final_file_name": "Votre document signé", "zipFile_Name": "Fichiers attachés" }\')');
(FPDF, PHP, SQL) table values after first page gets messy
I am using PHP and fPDF to create a PDF "invoice" and everything works perfectly fine on the first page but when the table has to go to the second page it only returns the first value from the sql query and everything goes to the rest goes to the third page and so on. This is the code that loops the table rows $sql=sprintf("SELECT * FROM rostosativos_invoice where id_proposta = '".$_GET['id']."';"); $res=mysqli_query($link, $sql); while ($r=mysqli_fetch_assoc($res)){ // produto = posição 5 // quantidade = posição 7 // precouni = posição 6 // soma = posição 9 //multicell $cellWidth=120;//tamanho da cell $cellHeight=6.5;//altura da cell //verificar se o texto passa a cell if($pdf->GetStringWidth($r['produto']) < $cellWidth){ //se não, não fazer nada $line=1; }else{ //~se estiver, ~então calcular a altura necessária para a cobrir a cell //ao dividir o texto para ajustar ao tamanho da cell //~depois contar quantas linhas são necessãrias para ajustar o texto na cell $textLength=strlen($r['produto']); //total text length $errMargin=10; //cell com margem de erro, just in case $startChar=0; //posição inicial para cada linha $maxChar=0; //Máxima caracteres numa linha, para incremetar mais tarde $textArray=array(); //Guardar as strings em cada linha $tmpString=""; //Guardar a string numa linha temporária while($startChar < $textLength){ //loop até ao fim do texto //loop até chegar ao máximo de caracteres while( $pdf->GetStringWidth( $tmpString ) < ($cellWidth-$errMargin) && ($startChar+$maxChar) < $textLength ) { $maxChar++; $tmpString=substr($r['produto'],$startChar,$maxChar); } //mover startChar para a próxima linha $startChar=$startChar+$maxChar; //depois adicionar para o array para saber quantas linhas serão necessárias array_push($textArray,$tmpString); //reset maxChar e tmpString $maxChar=0; $tmpString=''; } //receber o numero de linhas $line=count($textArray); } //usar MultiCell em vez de Cell //mas primeiro, como a MultiCell é sempre tratada como fim de linha, precisamos de //definir manualmente a posição xy para a próxima cell ficar ao lado. //guardar a posição x e y antes de escrever a multicell $xPos=$pdf->GetX(); $yPos=$pdf->GetY(); $pdf->MultiCell($cellWidth,$cellHeight,$r['produto'],1,'L'); //receber a posição para a próxima cell ao lado da multicell //e equilibrar o x com o tamanho da multicell $pdf->SetXY($xPos + $cellWidth , $yPos); //escrever as cells $pdf->Cell(15,($line * $cellHeight),$r['quantidade'],1,0); //adaptar a altura ao número de linhas $pdf->Cell(10,($line * $cellHeight),'UNI',1,0); //adaptar a altura ao número de linhas $pdf->Cell(25,($line * $cellHeight),$r['precouni'].chr(128),1,0); //adaptar a altura ao número de linhas $pdf->Cell(25,($line * $cellHeight),$r['soma'].chr(128),1,1); //adaptar a altura ao número de linhas } This is the full PHP code: class PDF extends TFPDF { // Page Header function Header() { require("../config.php"); $rows = mysqli_query($link, "SELECT * FROM rostosativos_invoice INNER JOIN rostosativos_empresas ON rostosativos_invoice.empresa = rostosativos_empresas.empresa where id_proposta ='".$_GET['id']."';"); $r = mysqli_fetch_assoc($rows); $id_empresa = $r['id_empresa']; $idproposta = $r['id_proposta']; $responsavel = $r['responsavel']; $empresa = $r['empresa']; $data = $r['data_registo']; $contribuinte = $r['contribuinte']; $assunto = $r['assunto']; $refcliente = $r['refcliente']; // Logo $this->SetY(4); $this->Image('../logo.png',10,6,30); // Arial bold 15 $this->SetFont('Arial','B',9); // Move to the right $this->Cell(90); // Title $this->Cell(100,10,iconv('UTF-8', 'windows-1252','Sede: Rua Azenha dos Latoeiros, 1-A || 2580-557 Ribafria '),'LTR',0,'C'); $this->Ln(5); $this->Cell(90); $this->Cell(100,10,iconv('UTF-8', 'windows-1252','Oficina: Estrada Nacional nº1 km 33.3'),'LR',0,'C'); $this->Ln(5); $this->Cell(90); $this->Cell(100,10,iconv('UTF-8', 'windows-1252','Quinta do Chacão, Casal Machado 2580-364 Alenquer '),'LR',0,'C'); $this->Ln(5); $this->Cell(90); $this->Cell(100,10,iconv('UTF-8', 'windows-1252','E-mail: geral#rostosativos.com'),'LR',0,'C'); $this->Ln(5); $this->Cell(90); $this->Cell(100,10,iconv('UTF-8', 'windows-1252','www.rostosativos.com'),'LR',0,'C'); $this->Ln(5); $this->Cell(90); $this->Cell(100,10,iconv('UTF-8', 'windows-1252','www.facebook.com/rostosativos/'),'LBR',0,'C'); // Line break $this->SetFont('Arial','',12); $this->Ln(15); $this->Cell(100 ,5,'',0,0); $this->Cell(35 ,5,'Proposta: ',0,0); $this->Cell(34 ,5, $idproposta,0,1);//end of line $this->Cell(100 ,5,'',0,0); $this->Cell(35 ,5,iconv('UTF-8', 'windows-1252','Ref. Cliente: '),0,0); $this->Cell(34 ,5,$refcliente,0,1);//end of line $this->Cell(100 ,5,'',0,0); $this->Cell(35 ,5,iconv('UTF-8', 'windows-1252','N.º Contribuinte: '),0,0); $this->Cell(34 ,5,$contribuinte,0,1);//end of line $this->Cell(100 ,5,'',0,0); $this->Cell(35 ,5,'Data: ',0,0); $this->Cell(34 ,5,$data,0,1);//end of line $this->Ln(5); //billing address $this->Cell(100 ,5,'Proposta para:',0,0);//end of line $this->Cell(100 ,5,'Assunto da proposta:',0,1);//end of line //add dummy cell at beginning of each line for indentation $this->Cell(10 ,5,'',0,0); $this->Cell(90 ,5,iconv('UTF-8', 'windows-1252',$empresa),0,0); $this->Cell(10 ,5,'',0,0); $this->Cell(90 ,5,iconv('UTF-8', 'windows-1252',$assunto),0,1); $this->Cell(10 ,5,'',0,0); $this->Cell(90 ,5,iconv('UTF-8', 'windows-1252',$responsavel),0,1); $this->Ln(2); //invoice contents $this->SetFont('Arial','B',12); $this->Cell(120 ,6.5,iconv('UTF-8', 'windows-1252','Designação'),1,0); $this->Cell(15 ,6.5,'Qtd.',1,0); $this->Cell(10 ,6.5,'UNI',1,0); $this->Cell(25, 6.5,iconv('UTF-8', 'windows-1252','Preço UNI.'),1,0); $this->Cell(25 ,6.5,'Total',1,1);//end of line } function Footer() { require("../config.php"); //~Tabela de Preço, etc.. $this->SetY(-20); $sql=sprintf("SELECT * FROM rostosativos_invoice where id_proposta = '".$_GET['id']."' ORDER BY id DESC LIMIT 1;"); $res=mysqli_query($link, $sql); while ($r=mysqli_fetch_assoc($res)){ $this->SetFont('Arial','',9); $this->Cell(30, 6,iconv('UTF-8', 'windows-1252','Exclusões:'),0,0); $this->Cell(15); $this->Cell(65 ,6,'',0,0); $this->SetFont('Arial','',11); $this->Cell(40 ,6,iconv('UTF-8', 'windows-1252','Soma'),0,0); $this->Cell(15); $this->Cell(30, 6, $r['totalsoma'].chr(128),1,1,'R'); $this->SetFont('Arial','',9); $this->Cell(30,6,iconv('UTF-8', 'windows-1252',$r['exclusao1']),0, 'L'); $this->SetFont('Arial','',11); $this->Cell(15); $this->Cell(65 ,6,'',0,0); $this->Cell(40 ,6,iconv('UTF-8', 'windows-1252','Mão de Obra'),0,0); $this->Cell(15); $this->Cell(30, 6, $r['maoobra'].chr(128),1,1,'R'); $this->SetFont('Arial','',9); $this->Cell(30,6,iconv('UTF-8', 'windows-1252',$r['exclusao2']),0, 'L'); $this->SetFont('Arial','',11); $this->Cell(80 ,6,'',0,0); $this->Cell(40 ,6,'Valor GLOBAL em EUROS',0,0); $this->Cell(15); $this->Cell(30 ,6,$r['precototal'].chr(128),1,1,'R');//end of line } // Position at 1.5 cm from bottom $this->SetY(-9); // Arial italic 8 $this->SetFont('Arial','I',8); // Page number $this->Cell(0,10,iconv('UTF-8', 'windows-1252','Página '.$this->PageNo().'/{nb}'),0,0,'C'); } } //A4 width : 219mm //default margin : 10mm each side //writable horizontal : 219-(10*2)=189mm //create pdf object $pdf = new PDF('P','mm','A4'); $pdf -> AliasNbPages(); //add new page $pdf->AddPage(); // Add a Unicode font (uses UTF-8) $pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true); $pdf->SetFont('DejaVu','',12); //set font to arial, regular, 12pt $pdf->SetFont('Arial','',12); $sql=sprintf("SELECT * FROM rostosativos_invoice where id_proposta = '".$_GET['id']."';"); $res=mysqli_query($link, $sql); while ($r=mysqli_fetch_assoc($res)){ // produto = posição 5 // quantidade = posição 7 // precouni = posição 6 // soma = posição 9 //multicell $cellWidth=120;//tamanho da cell $cellHeight=6.5;//altura da cell //verificar se o texto passa a cell if($pdf->GetStringWidth($r['produto']) < $cellWidth){ //se não, não fazer nada $line=1; }else{ //~se estiver, ~então calcular a altura necessária para a cobrir a cell //ao dividir o texto para ajustar ao tamanho da cell //~depois contar quantas linhas são necessãrias para ajustar o texto na cell $textLength=strlen($r['produto']); //total text length $errMargin=10; //cell com margem de erro, just in case $startChar=0; //posição inicial para cada linha $maxChar=0; //Máxima caracteres numa linha, para incremetar mais tarde $textArray=array(); //Guardar as strings em cada linha $tmpString=""; //Guardar a string numa linha temporária while($startChar < $textLength){ //loop até ao fim do texto //loop até chegar ao máximo de caracteres while( $pdf->GetStringWidth( $tmpString ) < ($cellWidth-$errMargin) && ($startChar+$maxChar) < $textLength ) { $maxChar++; $tmpString=substr($r['produto'],$startChar,$maxChar); } //mover startChar para a próxima linha $startChar=$startChar+$maxChar; //depois adicionar para o array para saber quantas linhas serão necessárias array_push($textArray,$tmpString); //reset maxChar e tmpString $maxChar=0; $tmpString=''; } //receber o numero de linhas $line=count($textArray); } //usar MultiCell em vez de Cell //mas primeiro, como a MultiCell é sempre tratada como fim de linha, precisamos de //definir manualmente a posição xy para a próxima cell ficar ao lado. //guardar a posição x e y antes de escrever a multicell $xPos=$pdf->GetX(); $yPos=$pdf->GetY(); $pdf->MultiCell($cellWidth,$cellHeight,$r['produto'],1,'L'); //receber a posição para a próxima cell ao lado da multicell //e equilibrar o x com o tamanho da multicell $pdf->SetXY($xPos + $cellWidth , $yPos); //escrever as cells $pdf->Cell(15,($line * $cellHeight),$r['quantidade'],1,0); //adaptar a altura ao número de linhas $pdf->Cell(10,($line * $cellHeight),'UNI',1,0); //adaptar a altura ao número de linhas $pdf->Cell(25,($line * $cellHeight),$r['precouni'].chr(128),1,0); //adaptar a altura ao número de linhas $pdf->Cell(25,($line * $cellHeight),$r['soma'].chr(128),1,1); //adaptar a altura ao número de linhas } //output the result $pdf->Output(); $content = $pdf->Output('propostas/'.$_GET['id'].'.pdf','F'); file_put_contents($content);
Make these changes right after you define the PDF and pages. $pdf = new PDF('P','mm','A4'); $pdf -> AliasNbPages(); $pdf->AddPage(); $pdf->SetAutoPageBreak(false); // add this line and the next $howhigh = $pdf->GetPageHeight(); // stash the height of the page for later The next change is in the else where the size of the larger cells is calculated. There is really no reason to go through the data to be added character by character. You can replace that block of code with: //verificar se o texto passa a cell if ($pdf->GetStringWidth($r['produto']) < $cellWidth) { //se não, não fazer nada $line=1; } else { $line = ceil($pdf->GetStringWidth($item[2])); $line = round($line / $cellWidth,0) + 1; } Finally, the actual output of the data needs a little change to account for testing whether or not we need to start a new page. As you'll see the calculation done above are used. //usar MultiCell em vez de Cell //mas primeiro, como a MultiCell é sempre tratada como fim de linha, precisamos de //definir manualmente a posição xy para a próxima cell ficar ao lado. //guardar a posição x e y antes de escrever a multicell $xPos=$pdf->GetX(); $yPos=$pdf->GetY(); $total = $yPos + (($line * $cellHeight)); if ($total > $howhigh) { // we will spill to a new page with this cell $pdf->AddPage(); // so start a new page before we add the cell $xPos=$pdf->GetX(); $yPos=$pdf->GetY(); } $pdf->MultiCell($cellWidth,$cellHeight,$r['produto'],1,'L'); //receber a posição para a próxima cell ao lado da multicell //e equilibrar o x com o tamanho da multicell $pdf->SetXY($xPos + $cellWidth , $yPos);
How can I use "for" inside an "array"?
Thank you for your help. I am working on a new site, i would love to generate a CSV from a XML website. But i can't use "for (number...)" inside an array. <?php // output headers so that the file is downloaded rather than displayed header('Content-type: text/csv'); header('Content-Disposition: attachment; filename="demo.csv"'); // do not cache the file header('Pragma: no-cache'); header('Expires: 0'); // create a file pointer connected to the output stream $file = fopen('php://output', 'w'); // send the column headers fputcsv($file, array('Column 1', 'Column 2', 'Column 3')); $json_string = "http://v2.notmaison.be/php/index.php?action=getRealEstateByNotaris¬aris=FRANCE,%20Gilles"; $jsondata = file_get_contents($json_string); $result = json_decode ($jsondata,true); $nombre = count($result['results']); $json = $result['results'][$numero]['im']; $json_decoded = json_decode($json); $data = array( for ($numero = 0; $numero < $nombre ; $numero++) { Array($result['results'][$numero]['re_ru'],"test2","test3") ); } // output each row of the data foreach ($data as $row) { fputcsv($file, $row); } exit(); ?> I have this error : Parse error: syntax error, unexpected 'for' (T_FOR), expecting ')' in /htdocs/biens3.php on line 25
you should use for ($numero = 0; $numero < $nombre ; $numero++) { $data[] = Array($result['results'][$numero]['re_ru'],"test2","test3"); }
Try declaring $data as an empty Array, then for each $nombre you add an item/Array to $data, something liek this: $data = Array(); for($numero = 0; $numero < $nombre; $numero++){ $data[] = Array($result['results'][$numero]['re_ru'],"test2","test3"); }
If your goal is to populate the array, instead of this: $data = array( for ($numero = 0; $numero < $nombre ; $numero++) { Array($result['results'][$numero]['re_ru'],"test2","test3") ); } You can first create the array like you're doing, but just create, and then add the elements with a loop: $data = []; # shorter syntax than array(), but the same. for ($numero = 0; $numero < $nombre ; $numero++) { $data[] = [ $result['results'][$numero]['re_ru'], "test2", "test3" ]; } The syntax $data[] will push elements to the end of the array. Note that you actually don't even need to create the array itself. I also noticed that right after you're looping on the array to output its contents. And since you don't use $data anywhere else after, you could eliminate it and ouptup data in the same loop: for ($numero = 0; $numero < $nombre ; $numero++) { fputcsv($file, [ $result['results'][$numero]['re_ru'], "test2", "test3" ]); );
This is a perfect candidate for the use of foreach rather than a for The code can be simplified down to this $json_string = "http://v2.notmaison.be/php/index.php?action=getRealEstateByNotaris¬aris=FRANCE,%20Gilles"; $jsondata = file_get_contents($json_string); $json_obj = json_decode ($jsondata); $csv_file = fopen('php://output', 'w'); foreach ( $json_obj->results as $result) { // to use all the fields from the json returned fputcsv($csv_file, (array)$result); } Giving output: 25174,CH-82691-16,0,50.4107048,4.4445519,2,12,1,,3,4,,"Appartement meublé (3ème étage) 2 chambres avec cave et garage.<br/>Hall, séjour, cuisine équipée, sdb, wc, buanderie, 2 chambres.<br/>Balcon avant avec tente solaire. Porte blindée. Cave. Garage. Ascenseur.<br/>",,6000,2,0,-1,95000,10,"Rue Basslé",Charleroi,0,1,0,1,-1,-1,1018,-1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 95000 €","S'adresser en l'étude.",-1,-1,-1,1,-1,-1,-1,-1,-1,-1,1,,,,,,,,,,,,"Classe B",201611231147,201611281115,contact#notairescharleroi.be,notaire.france#skynet.be,,20161109022084,,,HA,,,,,OFF,,2,Appartements,"un appartement",12,Appartement,Appartement,2,1,Gré-à-Gré,,,,,3,Central,4,Equipée,"[""WEBB-AFYESF"",""WEBB-AFYES7"",""WEBB-AFYES9""]",238 22691,CH-82112-16,0,50.4234543,4.4862727,1,8,1,,9,2,,"Maison de rapport avec 2 appartements.<br/>Hall commun de +/- 16 m².<br/>Appartement rez (+/- 45 m²): chambre (+/- 18 m²), séjour-sàm (+/- 10 m²), cuisine (+/- 4 m²), sdb (+/- 2,5 m²), cour arrière.<br/>Appartement 1er étage (+/- 51 m²): séjour-sàm (+/- 29 m²), chambre (+/- 17 m²), sdb (+/- 3 m²).<br/>Grenier aménageable (+/- 70 m²).<br/>Châssis SV.","Libre à l'acte.",6060,2,60,-1,80000,114,"Rue Hanoteau",Gilly,0,-1,0,0,1,-1,594,-1,-1,-1,-1,-1,1,-1,2,2,-1,-1,-1,2,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 80000 €","S'adresser en l'étude.",1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,"Classe E",201607191431,201607250944,contact#notairescharleroi.be,notaire.france#skynet.be,,20160228005227,,,HA,,,,,OFF,,1,Maisons,"une maison",8,"Maison de rapport",Opbrengsteigendom,1,1,Gré-à-Gré,,,,,9,"Foyer gaz",2,"Non équipée","[""WEBB-ABZGY2"",""WEBB-ABZGY5""]",238 15311,CH-80259-15,0,50.4291858,4.4990644,1,7,1,,5,2,,"Maison avec jardin.<br/>Sous-sol: cave.<br/>Rez: sàm, living.<br/>Annexe: cuisine, sdb avec wc séparé, buanderie.<br/>Etage: 2 chambres.<br/>Grenier, jardin.<br/>Châssis PVC double vitrage.",,6060,2,432,-1,55000,31,"Rue Brasserie Gillieaux",Gilly,0,-1,1,0,-1,-1,282,-1,-1,1,-1,-1,-1,1,-1,1,-1,-1,-1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 55000 €","S'adresser en l'étude.",-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,"Classe G",201509011601,201601060955,contact#notairescharleroi.be,notaire.france#skynet.be,G,20150507024064,513,60394,HA,,,,,OFF,,1,Maisons,"une maison",7,"Maison d'habitation",Woonhuis,1,1,Gré-à-Gré,,,,,5,"Central mazout",2,"Non équipée","[""WEBB-9ZXJLP"",""WEBB-9ZXJLS"",""WEBB-9ZXJMS""]",238 24222,CH-82449-16,0,50.4276111,4.472657,4,39,1,,4,2,,"Immeuble de rapport avec commerce (et cour) au rez et 2 appartements.<br/>Sous-sol de 65 m².<br/>Rez commercial de 70 m²: commerce et pièce arrière avec WC. Cour.<br/>1er étage: appartement de 63 m² avec balcon: cuisine, séjour/sàm, hall, 1 chambre, sdb.<br/>2ème étage: appartement de 70 m² avec balcon: cuisine, séjour/sàm, débarras, hall, WC, sdb, 1 chambre.<br/>CC gaz, 3 chaudières séparées.<br/>citerne eau de pluie. Compteurs gaz et électricité séparés.",,6060,2,147,-1,160000,198,"Chaussée de Lodelinsart",Gilly,0,-1,0,0,-1,-1,1682,-1,-1,2,-1,-1,2,-1,2,2,-1,-1,-1,2,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 160000 €","S'adresser en l'étude.",-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,,,,,,,,,,,,"Classe G",201610101349,201610191534,contact#notairescharleroi.be,notaire.france#skynet.be,,20161003008071,,,HA,,,,,OFF,,4,"Bureaux / Commerces","un bureau / commerce",39,"Maison de rapport",Opbrengsteigendom,4,1,Gré-à-Gré,,,,,4,"Central gaz",2,"Non équipée","[""WEBB-AELG3S"",""WEBB-AEVHX6"",""WEBB-AEVHX8"",""WEBB-AEVHXA"",""WEBB-AEVHXC"",""WEBB-AEVHXE""]",238 24617,CH-82546-16,0,50.3780923,4.3711288,1,7,1,,4,1,5,"Sous-sol : caves<br/>Rez-de-chaussée (40 m²) : hall, séjour, cuisine<br/>1er étage (40m²) : hall, 2 chambres, salle de bain <br/>Grenier aménageable<br/>Jardin et cour<br/>Garage<br/>Chauffage central au gaz <br/>Châssis double vitrage PVC et aluminium<br/>R.C.: 431,00 €<br/>Superficie : 3 ares 30 centiares<br/>PEB N° 20161020028100: classe E<br/>Faire offre à partir de 85.000,00 € . <br/>Offre actuelle : 85.000,00 €.<br/> <br/>",,6110,2,330,-1,85000,334,"Rue de Gozée",Montigny-le-Tilleul,3,-1,1,1,1,-1,431,-1,-1,1,-1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,2,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 85000 €","S'adresser en l'étude.",0,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,,201610261444,201611080845,contact#notairescharleroi.be,notaire.france#skynet.be,,20161020028100,,,HA,,,,,OFF,,1,Maisons,"une maison",7,"Maison d'habitation",Woonhuis,1,1,Gré-à-Gré,,,5,Bon,4,"Central gaz",1,Présente,"[""WEBB-AF4H3P""]",238 25383,CH-82753-16,0,50.3439488,4.4577754,3,18,1,,,,,"Terrain de 9 ares 58ca.<br/>Lot sous teinte blanche.",,6120,0,958,-1,85000,,"Rue de la Ferrée",Nalinnes,0,-1,0,0,-1,-1,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 85000 €","Sur place.",-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,,201612021139,201612021141,contact#notairescharleroi.be,notaire.france#skynet.be,,,,,HA,,,,,OFF,,3,Terrains,"un terrain",18,"Prairies / pâtures",Weide,3,1,Gré-à-Gré,,,,,,,,,"[""WEBB-AG9EJM"",""WEBB-AG9EJP""]",238 18716,CH-81190-16,0,50.4239506,4.4872409,1,7,1,,5,2,,"Maison avec jardin.<br/>Sous-sol: cave avec voussettes.<br/>Rez: hall, séjour-sàm, WC.<br/>Annexe: cuisine, sdb.<br/>1er étage: hall, 3 chambres.<br/>Annexe au 1er étage: 1 chambre, WC, pièce.<br/>Grenier aménageable.<br/>Jardin à l'arrière. Châssis DV en partie et volets en partie.<br/>",,6060,4,220,-1,80000,11,"Rue de la Station",Gilly,0,-1,1,0,1,-1,773,-1,-1,2,-1,-1,1,-1,1,1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 80000 €","S'adresser en l'étude.",-1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,"Classe G",201602050944,201608081422,contact#notairescharleroi.be,notaire.france#skynet.be,G,20160128025502,528,,HA,,,,,OFF,,1,Maisons,"une maison",7,"Maison d'habitation",Woonhuis,1,1,Gré-à-Gré,,,,,5,"Central mazout",2,"Non équipée","[""WEBB-A6UCCX"",""WEBB-A6UCCY"",""WEBB-A6UCD2""]",238 25159,CH-82686-16,0,50.4253111,4.501545,1,7,1,,,2,,"Maison 3 façades avec jardin.<br/>Sous-sol: caves.<br/>Rez: séjour, sàm avec coin cuisine, WC.<br/>1er étage: hall, 2 chambres.<br/>Grenier aménageable. Jardin.<br/>chauffage au charbon.<br/>Châssis DV PVC sauf un en façade.",,6060,2,350,-1,60000,47,"Rue de la Plateure",Gilly,3,-1,1,0,1,-1,297,-1,-1,1,-1,-1,1,-1,1,1,-1,-1,-1,0,-1,-1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 60000 €","S'adresser en l'étude.",-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,"Classe G",201611221617,201611221625,contact#notairescharleroi.be,notaire.france#skynet.be,,201604280334591,,,HA,,,,,OFF,,1,Maisons,"une maison",7,"Maison d'habitation",Woonhuis,1,1,Gré-à-Gré,,,,,,,2,"Non équipée","[""WEBB-AFXL43"",""WEBB-AFXL4H""]",238 24585,CH-82540-16,0,50.422774,4.4799037,2,12,1,,4,4,,"Appartement (2ème étage) comprenant hall, séjour, cuisine (frigo, four électrique et hotte), sdb avec douche multi confort, chambre.<br/>Balcon arrière, cave.",,6060,1,0,-1,55000,5,"Chaussée de Lodelinsart",Gilly,0,1,0,0,-1,-1,706,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 55000 €","S'adresser en l'étude.",-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,"Classe F",201610251409,201610251416,contact#notairescharleroi.be,notaire.france#skynet.be,,20161017025827,,,HA,,,,,OFF,,2,Appartements,"un appartement",12,Appartement,Appartement,2,1,Gré-à-Gré,,,,,4,"Central gaz",4,Equipée,"[""WEBB-AF3GDJ"",""WEBB-AF3GDL""]",238 22272,CH-82012-16,0,50.40205,4.5199634,1,7,1,,3,2,,"Maison avec dépendances et garage.<br/>Rez (+/- 50 m²): hall, cuisine, 1 pièce.<br/>1er étage (+/- 65 m²): hall, 4 chambres.<br/>2ème étage (+/- 60 m²): hall, sdb, 3 chambres.<br/>Grenier (+/- 45 m²) aménageable.<br/>Chauffage central, terrasse, jardin.<br/>RC du n°72: 535€ - RC du n°74: 97€.",,6200,7,228,-1,80000,72/74,"Rue d'Acoz",Châtelet,0,1,1,1,1,-1,632,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 80000 €","S'adresser en l'étude.",-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,"Classe G",201606291112,201606291117,contact#notairescharleroi.be,notaire.france#skynet.be,,20160120016969,,,HA,,,,,OFF,,1,Maisons,"une maison",7,"Maison d'habitation",Woonhuis,1,1,Gré-à-Gré,,,,,3,Central,2,"Non équipée","[""WEBB-ABDCWC"",""WEBB-ABDCWJ""]",238 22955,CH-82160-16,0,50.1681918,4.3181224,1,2,1,,9,4,5,"Châlet de 65m² meublé avec jardin comprenant :<br/> <br/>Living, cuisine, 2 chambres, salle de bains <br/>Jardin avec deux chalets <br/>Convecteurs pétrole avec thermostat<br/>Boiler au gaz <br/>PEB : F<br/>",,6440,2,280,-1,50000,314,"Parc Résidentiel Le Bosquet",Fourbechies,4,-1,1,0,-1,1,265,-1,-1,1,-1,-1,-1,1,-1,-1,-1,-1,-1,1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 50000 €","S'adresser en l'étude.",2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,,,,,,,,,,,,,201608081032,201608081036,contact#notairescharleroi.be,notaire.france#skynet.be,,20160707022876,,,HA,,,,,OFF,,1,Maisons,"une maison",2,Châlet,Chalet,1,1,Gré-à-Gré,,,5,Bon,9,"Foyer gaz",4,Equipée,"[""WEBB-ACMC4J"",""WEBB-ACMC4S"",""WEBB-ACMC4X""]",238 25119,CH-82675-16,0,50.4328324,4.467517,1,7,1,4,2,,3,"Maison incendiée 3 façades avec jardin composée de :<br/>Sous-sol : caves.<br/>Rez-de-chaussée : + 43m²<br/>1er étage: + 43m²<br/>Grenier aménageable<br/>Jardin <br/>Offres à partir de 60.000,00€<br/>Offre actuelle : 75.000,00 €<br/><br/><br/> <br/> <br/><br/>",,6060,1,367,-1,60000,111,"Rue Chausteur",Gilly,3,-1,1,0,1,0,609,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,"FRANCE, Gilles","Maison du notariat de Charleroi",071/41.45.34,071/20.56.56,"Faire offre à partir de: 60000 €","S'adresser en l'étude.",0,-1,0,-1,-1,-1,-1,-1,-1,-1,0,,,,,,,,,,,,,201611210950,201612051553,contact#notairescharleroi.be,notaire.france#skynet.be,,,,,HA,,,,,OFF,,1,Maisons,"une maison",7,"Maison d'habitation",Woonhuis,1,1,Gré-à-Gré,4,Oui,3,Mauvais,2,"A installer",,,"[""WEBB-AFWCFT""]",238 Or if you only want specific fields from the json $json_string = "http://v2.notmaison.be/php/index.php?action=getRealEstateByNotaris¬aris=FRANCE,%20Gilles"; $jsondata = file_get_contents($json_string); $json_obj = json_decode ($jsondata); $csv_file = fopen('php://output', 'w'); foreach ( $json_obj->results as $result) { // to use only specific fields from the input fputcsv($csv_file, array($result->re_nu, $result->re_ru) ); } Giving a csv like this 10,"Rue Basslé" 114,"Rue Hanoteau" 31,"Rue Brasserie Gillieaux" 198,"Chaussée de Lodelinsart" 334,"Rue de Gozée" ,"Rue de la Ferrée" 11,"Rue de la Station" 47,"Rue de la Plateure" 5,"Chaussée de Lodelinsart" 72/74,"Rue d'Acoz" 314,"Parc Résidentiel Le Bosquet" 111,"Rue Chausteur" EDIT for second question If you want the Images codes included in your output then this would do it foreach ( $json_obj->results as $result) { $required = array(); // init an array // pick fields wanted in resulting csv $required[] = $result->re_nu; $required[] = $result->re_ru; // get the images $im_codes = json_decode($result->im); foreach ($im_codes as $im) { $required[] = 'http://photos.notmaison.be/photos/m' . $im . '.jpg'; } fputcsv($csv_file, $required); } Generated output: 10,"Rue Basslé",http://photos.notmaison.be/photos/mWEBB-AFYESF.jpg,http://photos.notmaison.be/photos/mWEBB-AFYES7.jpg,http://photos.notmaison.be/photos/mWEBB-AFYES9.jpg 114,"Rue Hanoteau",http://photos.notmaison.be/photos/mWEBB-ABZGY2.jpg,http://photos.notmaison.be/photos/mWEBB-ABZGY5.jpg 31,"Rue Brasserie Gillieaux",http://photos.notmaison.be/photos/mWEBB-9ZXJLP.jpg,http://photos.notmaison.be/photos/mWEBB-9ZXJLS.jpg,http://photos.notmaison.be/photos/mWEBB-9ZXJMS.jpg 198,"Chaussée de Lodelinsart",http://photos.notmaison.be/photos/mWEBB-AELG3S.jpg,http://photos.notmaison.be/photos/mWEBB-AEVHX6.jpg,http://photos.notmaison.be/photos/mWEBB-AEVHX8.jpg,http://photos.notmaison.be/photos/mWEBB-AEVHXA.jpg,http://photos.notmaison.be/photos/mWEBB-AEVHXC.jpg,http://photos.notmaison.be/photos/mWEBB-AEVHXE.jpg 334,"Rue de Gozée",http://photos.notmaison.be/photos/mWEBB-AF4H3P.jpg ,"Rue de la Ferrée",http://photos.notmaison.be/photos/mWEBB-AG9EJM.jpg,http://photos.notmaison.be/photos/mWEBB-AG9EJP.jpg 11,"Rue de la Station",http://photos.notmaison.be/photos/mWEBB-A6UCCX.jpg,http://photos.notmaison.be/photos/mWEBB-A6UCCY.jpg,http://photos.notmaison.be/photos/mWEBB-A6UCD2.jpg 47,"Rue de la Plateure",http://photos.notmaison.be/photos/mWEBB-AFXL43.jpg,http://photos.notmaison.be/photos/mWEBB-AFXL4H.jpg 5,"Chaussée de Lodelinsart",http://photos.notmaison.be/photos/mWEBB-AF3GDJ.jpg,http://photos.notmaison.be/photos/mWEBB-AF3GDL.jpg 72/74,"Rue d'Acoz",http://photos.notmaison.be/photos/mWEBB-ABDCWC.jpg,http://photos.notmaison.be/photos/mWEBB-ABDCWJ.jpg 314,"Parc Résidentiel Le Bosquet",http://photos.notmaison.be/photos/mWEBB-ACMC4J.jpg,http://photos.notmaison.be/photos/mWEBB-ACMC4S.jpg,http://photos.notmaison.be/photos/mWEBB-ACMC4X.jpg 111,"Rue Chausteur",http://photos.notmaison.be/photos/mWEBB-AFWCFT.jpg
I need to output in the same time [""WEBB-AFYESF"",""WEBB-AFYES7"",""WEBB-AFYES9""] to CSV as "http://photos.notmaison.be/photos/mWEBB-AFYESF.jpg", "http://photos.notmaison.be/photos/mWEBB-AFYES7.jpg", "http://photos.notmaison.be/photos/mWEBB-AFYES9.jpg"
automatic form submission with CURL php
I can not run this script, I have every time two error messages can you help me (!) Warning: DOMDocument :: loadHTML (): Empty string Supplied as input in C: \ wamp \ www \ form \ formulaire.php on line 23 0.1442 2 142344 loadHTML () .. \ formulaire.php: 23 Notice (!): Undefined variable: description in C: \ wamp \ www \ form \ formulaire.php on line 57 <?php //La page qu'on veut utiliser $wikipediaURL = 'http://fr.wikipedia.org/wiki/Megadeth'; //On initialise cURL $ch = curl_init(); //On lui transmet la variable qui contient l'URL curl_setopt($ch, CURLOPT_URL, $wikipediaURL); //On lui demdande de nous retourner la page curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //On envoie un user-agent pour ne pas être considéré comme un bot malicieux curl_setopt($ch, CURLOPT_USERAGENT, 'Le blog de Samy Dindane (www.dinduks.com'); //On exécute notre requête et met le résultat dans une variable $resultat = curl_exec($ch); //On ferme la connexion cURL curl_close($ch); //On crée un nouveau document DOMDocument $wikipediaPage = new DOMDocument(); //On y charge le contenu qu'on a récupéré avec cURL $wikipediaPage->loadHTML($resultat); //On parcourt les balises <div> foreach($wikipediaPage->getElementsByTagName('div') as $div){ //Si l'id de la page est bodyContent if($div->getAttribute('id') == "bodyContent"){ //On met le contenu du premier <p> dans une variable $premierP = trim($div->getElementsByTagName('p')->item(0)->nodeValue); //Si le premier <p> est vide ou ne contient pas du texte while($premierP == '<br>' || $premierP == '<br />' || $premierP == ''){ //On le supprime $div->removeChild($div->getElementsByTagName('p')->item(0)); //Et on passe au <p> suivant $premierP = trim($div->getElementsByTagName('p')->item(0)->nodeValue); }; //Un joli try pour éviter les messages d'erreur try{ //On parcourt toutes les tables foreach( $div->getElementsByTagName('table') as $table ){ //Et on les supprime $div->removeChild($table); } } catch(Exception $e){ //On censure :P } //On récupère le contenu de la fameuse balise <p> dans une variable $description = '<p>' . $div->getElementsByTagName('p')->item(0)->nodeValue. '</p>'; } } //On enlève la syntaxe propre à Wikipedia $description = preg_replace('/\[[0-9]*\][,]|\[[0-9]*\]/', '', $description); //On affiche de résultat echo $description; ?> Hello I tackled too big so I gave up Thanks for your help
Check out Simple Html Dom. It really simplifies finding stuff in html files. Here is an example with your code. <?php include("simple_html_dom.php"); $wikipediaURL = 'http://fr.wikipedia.org/wiki/Megadeth'; $html = file_get_html($wikipediaURL); $description = '<p>' .$html->find('p', 0). '</p>'; $description = preg_replace('/\[[0-9]*\][,]|\[[0-9]*\]/', '', $description); echo $description; Simple Html Dom Documentation
Try this $resultat = file_get_contents('http://fr.wikipedia.org/wiki/Megadeth');
making payments through mercanet in PHP
In an e-commerce website for a company located in France we want to take payments through Mercanet (BNP Paribas). I downloaded API's for linux, it only contains two binary files (request, response) there are no PHP examples. No answer from helpdesk either. Also I downloaded the certificate for the website, but just stuck as there is no howto files.
TO anybody out there pulling their hair out with the ATOS / Mercanet / Sips payment system, below is an example of the PHP file they sent me. All their help docs is in french. It is important to note that there are 32 and 64 bit versions - you have to use correct one. I tried the tricks mentioned here https://translate.googleusercontent.com/translate_c?depth=1&hl=en&prev=search&rurl=translate.google.co.za&sl=fr&u=http://www.developpez.net/forums/d599959/webmasters-developpement-web/general-conception-web/e-commerce/probleme-d-installation-d-plug-in-mercanet/&usg=ALkJrhj4iJ0kxEE9EoUbQTjq_0peu4_PSQ FTP trick did not work. https://translate.googleusercontent.com/translate_c?depth=1&hl=en&prev=search&rurl=translate.google.co.za&sl=fr&u=http://www.developpez.net/forums/d1154720/webmasters-developpement-web/general-conception-web/e-commerce/probleme-d-installation-d-plug-in-mercanet/&usg=ALkJrhiEypDQCmEu5uVWD5uDpOChAAaNbQ 32bit hack did not work this give you pretty good instructions. translations looks good enough to make sense of it https://translate.googleusercontent.com/translate_c?depth=1&hl=en&prev=search&rurl=translate.google.co.za&sl=fr&u=http://thierry-godin.developpez.com/php/atos/&usg=ALkJrhjC12cJksMlauYxLvwnoxPV0G__9g the only thing that worked was having the correct version. also remember if you using git, a push may reset permissions, then you have to 755 the request file everytime you push. PHP example: print ("<HTML><HEAD><TITLE>MERCANET - Paiement Securise sur Internet</TITLE></HEAD>"); print ("<BODY bgcolor=#ffffff>"); print ("<Font color=#000000>"); print ("<center><H1>Test de l'API plug-in MERCANET</H1></center><br><br>"); // Affectation des paramètres obligatoires $parm="merchant_id=082584341411111"; $parm="$parm merchant_country=fr"; $parm="$parm amount=100"; $parm="$parm currency_code=978"; // Initialisation du chemin du fichier pathfile (à modifier) // ex : // -> Windows : $parm="$parm pathfile=c:/repertoire/pathfile"; // -> Unix : $parm="$parm pathfile=/home/repertoire/pathfile"; $parm="$parm pathfile=" . XOOPS_ROOT_PATH.'/tray_code/payment_gateways/sips/param/pathfile'; // Si aucun transaction_id n'est affecté, request en génère // un automatiquement à partir de heure/minutes/secondes // Référez vous au Guide du Programmeur pour // les réserves émises sur cette fonctionnalité // // $parm="$parm transaction_id=123456"; // Affectation dynamique des autres paramètres // Les valeurs proposées ne sont que des exemples // Les champs et leur utilisation sont expliqués dans le Dictionnaire des données // // $parm="$parm normal_return_url=http://www.maboutique.fr/cgi-bin/call_response.php"; // $parm="$parm cancel_return_url=http://www.maboutique.fr/cgi-bin/call_response.php"; // $parm="$parm automatic_response_url=http://www.maboutique.fr/cgi-bin/call_autoresponse.php"; // $parm="$parm language=fr"; // $parm="$parm payment_means=CB,2,VISA,2,MASTERCARD,2"; // $parm="$parm header_flag=no"; // $parm="$parm capture_day="; // $parm="$parm capture_mode="; // $parm="$parm bgcolor="; // $parm="$parm block_align="; // $parm="$parm block_order="; // $parm="$parm textcolor="; // $parm="$parm receipt_complement="; // $parm="$parm caddie=mon_caddie"; // $parm="$parm customer_id="; // $parm="$parm customer_email="; // $parm="$parm customer_ip_address="; // $parm="$parm data="; // $parm="$parm return_context="; // $parm="$parm target="; // $parm="$parm order_id="; // Les valeurs suivantes ne sont utilisables qu'en pré-production // Elles nécessitent l'installation de vos fichiers sur le serveur de paiement // // $parm="$parm normal_return_logo="; // $parm="$parm cancel_return_logo="; // $parm="$parm submit_logo="; // $parm="$parm logo_id="; // $parm="$parm logo_id2="; // $parm="$parm advert="; // $parm="$parm background_id="; // $parm="$parm templatefile="; // insertion de la commande en base de données (optionnel) // A développer en fonction de votre système d'information // Initialisation du chemin de l'executable request (à modifier) // ex : // -> Windows : $path_bin = "c:/repertoire/bin/request"; // -> Unix : $path_bin = "/home/repertoire/bin/request"; // $path_bin = XOOPS_ROOT_PATH.'/tray_code/payment_gateways/sips/bin/static/request'; // Appel du binaire request // La fonction escapeshellcmd() est incompatible avec certaines options avancées // comme le paiement en plusieurs fois qui nécessite des caractères spéciaux // dans le paramètre data de la requête de paiement. // Dans ce cas particulier, il est préférable d.exécuter la fonction escapeshellcmd() // sur chacun des paramètres que l.on veut passer à l.exécutable sauf sur le paramètre data. $parm = escapeshellcmd($parm); $result=exec("$path_bin $parm"); // sortie de la fonction : $result=!code!error!buffer! // - code=0 : la fonction génère une page html contenue dans la variable buffer // - code=-1 : La fonction retourne un message d'erreur dans la variable error //On separe les differents champs et on les met dans une variable tableau $tableau = explode ("!", "$result"); // récupération des paramètres $code = $tableau[1]; $error = $tableau[2]; $message = $tableau[3]; // analyse du code retour if (( $code == "" ) && ( $error == "" ) ) { print ("<BR><CENTER>erreur appel request</CENTER><BR>"); print ("executable request non trouve $path_bin"); } // Erreur, affiche le message d'erreur else if ($code != 0){ print ("<center><b><h2>Erreur appel API de paiement.</h2></center></b>"); print ("<br><br><br>"); print (" message erreur : $error <br>"); } // OK, affiche le formulaire HTML else { print ("<br><br>"); # OK, affichage du mode DEBUG si activé print (" $error <br>"); print (" $message <br>"); } print ("</BODY></HTML>");