Error in loop with DOM PHP - php

I'm having two errors, can't get this to work...
With the code like this:
<html>
<body>
<?php
/*
Fontes:
- http://blog.clares.com.br/gerando-xml-com-php/
- https://forum.imasters.com.br/topic/482006-resolvido%C2%A0gerar-nomes-aleat%C3%B3rios/
*/
header('Content-type: text/xml; charset=utf-8');
if(empty($_POST["Pergunta"])) {
$pergunta = "";
echo "dar um alert e voltar";
} else {
$pergunta = $_POST["Pergunta"];
}
if(empty($_POST["Resposta"])) {
$resposta = "";
echo "dar um alert e voltar";
} else {
$resposta = $_POST["Resposta"];
$teste = explode("\n",$resposta);
echo '<pre>' . print_r($teste) . '</pre>';
}
/* CHECKBOX
if(isset($_POST['MostrarAIML'])){
//echo "checkbox marcado! <br/>";
//echo "valor: " . $_POST['MostrarAIML'];
$MostrarAIML = true;
}else{
//echo "checkbox não marcado! <br/>";
$MostrarAIML = false;
}
if(isset($_POST['SalvarAIML'])){
//echo "checkbox marcado! <br/>";
//echo "valor: " . $_POST['SalvarAIML'];
$SalvarAIML = true;
}else{
//echo "checkbox não marcado! <br/>";
$SalvarAIML = false;
} */
if(empty($_POST["forma"])) {
$escolhe = "MostrarAIML";
} else if($_POST["forma"]=='MostrarAIML'){
$escolhe = "MostrarAIML";
} else if($_POST["forma"]=='SalvarAIML'){
$escolhe = "SalvarAIML";
}
function nome_aleatorio(){
$tamanho = mt_rand(5,9);
$all_str = "abcdefghijlkmnopqrstuvxyzwABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$nome = "";
for ($i = 0;$i <= $tamanho;$i++){
$nome .= $all_str[mt_rand(0,61)];
}
return $nome;
}
# versao do encoding xml
$dom = new DOMDocument("1.0", "UTF-8");
# retirar os espacos em branco
$dom->preserveWhiteSpace = false;
# gerar o codigo
$dom->formatOutput = true;
# criando o nó principal (root)
$root = $dom->createElement("aiml");
$comentario = $dom->createComment("Copyright ©2017 - FAST.aiml
URL: http://avatar.cinted.ufrgs.br/alunos/fabricio/fastaiml/
Powered by Fabricio Herpich < fabricio_herpich at hotmail.com >
Project coordinator: Liane Margarida Rockenbach Tarouco < liane at penta.ufrgs.br >");
# nó filho (category)
$category = $dom->createElement("category");
# nó filho (pattern) / #setanto a pergunta
$pattern = $dom->createElement("pattern", $pergunta);
# nó filho (template) / #setanto a resposta
$template = array();
for($i = 0; $i < sizeof($teste); $i++){
$template[$i] = $dom->createElement("template", $teste[$i]);
}
# adiciona os nós em aiml
$category->appendChild($comentario);
$category->appendChild($pattern);
for($i = 0; $i < sizeof($template); $i++){
$category->appendChild($template[$i]);
}
# adiciona o nó contato em (root) agenda
$root->appendChild($category);
$dom->appendChild($root);
# busco um nome aleatório
$nome_arquivo = nome_aleatorio();
$dom->save("backup__/" . $nome_arquivo . ".xml");
if($escolhe == "MostrarAIML"){
# imprime o xml na tela
print $dom->saveXML();
}
if($escolhe == "SalvarAIML"){
# imprime o xml na tela
print $dom->saveXML();
# salva o arquivo AIML.xml
header("Content-Disposition: attachment; filename=fastaiml_" . $nome_arquivo . ".xml");
}
?>
</body>
</html>
I'm getting this error:
This page contains the following errors:
error on line 12 at column 18: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.**
I have other php file that works perfectly, where the header() function is after the $nome_arquivo = nome_aleatorio();
But, In this case I don't have the for loops on the code, 'cause I only have one for the file...and in this case I have to put multiple inside the tag...
If I put the header() like the other file, I get:
This page contains the following errors:
error on line 7 at column 18: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.**
how to work around this?

Related

Display all data from an API in PHP

I want to display all data I want from Matomo API but I can only display them one by one
I don't know if I should do a for loop and where or how.
My code :
<?php
include 'TabMetrique.php';
$token_auth = '*********';
getMetrique($metrique);
$url = "http://localhost/matomo/";
$url .= "?module=API&method=".getMetrique($metrique)."&idSite=1";
$url .= "&period=month&date=2022-05-14";
$url .= "&format=JSON";
$url .= "&token_auth=$token_auth";
$fetched = file_get_contents($url);
$content = json_decode($fetched,true);
// case error
if (!$content) {
print("No data found");
}
else {
print("<h1>Métrique Matomo</h1>\n");
foreach ($content as $row) {
if ($content == $row){
$contentMetrique = htmlspecialchars($row["label"], ENT_QUOTES, 'UTF-8'); // à changer pour afficher toute les métrique
$hits = $row['nb_visits'];
print("<b>$contentMetrique</b> ($hits visits)<br>\n");
}else{
print("$row<b> action or visit</b>");
}
}
}
?>
My IF condition doesn't work but that's not a problem at the moment
And TabMetrique.php :
<?php
$metrique [0] = 'DevicesDetection.getModel'; // appareil utilisé
$metrique [1] = 'UserCountry.getCountry'; // Pays
$metrique [2] = 'UserCountry.getContinent'; //continent
$metrique [3] = 'UserCountry.getRegion'; // Region
$metrique [4] = 'UserCountry.getCity'; // Ville
$metrique [5] = 'UserId.getUsers'; // recupérer les UsersID
$metrique [6] = 'UserLanguage.getLanguage'; // Langue
$metrique [7] = 'VisitFrequency.get'; // Visiteur récurrent
$metrique [8] = 'VisitsSummary.get';
$metrique [9] = 'VisitsSummary.getVisits'; //visiteur
$metrique [10] = 'VisitsSummary.getUniqueVisitors'; // visiteur unique
function getMetrique($metrique){
return $metrique[9];
}
?>
someone can help me ? thx
Well first remove the function it is unnecessary, all you need is an array and then process it with a forech loop.
code TabMetrique.php
<?php
$metrique[0] = 'DevicesDetection.getModel'; // appareil utilisé
$metrique[1] = 'UserCountry.getCountry'; // Pays
$metrique[2] = 'UserCountry.getContinent'; //continent
$metrique[3] = 'UserCountry.getRegion'; // Region
$metrique[4] = 'UserCountry.getCity'; // Ville
$metrique[5] = 'UserId.getUsers'; // recupérer les UsersID
$metrique[6] = 'UserLanguage.getLanguage'; // Langue
$metrique[7] = 'VisitFrequency.get'; // Visiteur récurrent
$metrique[8] = 'VisitsSummary.get';
$metrique[9] = 'VisitsSummary.getVisits'; //visiteur
$metrique[10] = 'VisitsSummary.getUniqueVisitors'; // visiteur unique
?>
Now a simple foreach loop to control getting the names from the metrique array
<?php
include 'TabMetrique.php';
$token_auth = '*********';
$url = "http://localhost/matomo/?";
$url .= "period=month&date=2022-05-14";
$url .= "&format=JSON&module=API";
$url .= "&token_auth=$token_auth&idSite=1";
foreach ($metrique as $metric) {
//get static part of the url and add dynamic bit to it
// note i moved the dynamic part to be last, that should not matter to the api
$u = $url . "&method=$metric";
$content = json_decode(file_get_contents($u), true);
// case error
if (!$content) {
print("No data found");
} else {
print("<h1>Métrique Matomo</h1>\n");
foreach ($content as $row) {
if ($content == $row){
$contentMetrique = htmlspecialchars($row["label"], ENT_QUOTES, 'UTF-8'); // à changer pour afficher toute les métrique
$hits = $row['nb_visits'];
print("<b>$contentMetrique</b> ($hits visits)<br>\n");
}else{
print("$row<b> action or visit</b>");
}
}
}
}

odbc_result echos data instead of saving it to variable

I have some code which uses odbc calls. I've had no problem with the pulling data from a MS SQL database until this bit of code. Instead of saving the string to a variable it outputs the string and saves an int 1 to the variable instead.
below is the relevant code:
$qry = 'SELECT * FROM cst_AdEssayDetails_vw WHERE AdEnrollSchedID = ?';
$essay = odbc_prepare($conn,$qry);
if(odbc_execute($essay,array($AdEnrollSchedID))){
if (odbc_num_rows($essay)>0){
while (odbc_fetch_row($essay)){
$setTopic = odbc_result($essay,'setTopic');
$essay_active = odbc_result($essay,'active');
$essay_date = date("m-d-y", strtotime(odbc_result($essay,'StartDate')));
$essayID = odbc_result($essay,'EssayID');
$EnrollSchedID = odbc_result($essay,'AdEnrollSchedID');
$intro = odbc_result($essay,'intro');
$support = odbc_result($essay,'support');
$conclusion = odbc_result($essay,'conclusion');
$essay_comment = odbc_result($essay,'comment');
$submitted = odbc_result($essay,'submitted');
$dateSubmitted = date("m-d-y", strtotime(odbc_result($essay,'dateSubmitted')));
$essay_grade = odbc_result($essay,'grade');
$AdStudentEssayID = odbc_result($essay,'AdStudentEssayID');
$topic = odbc_result($essay,'topic');
echo '<intro1>'.$intro.'</intro1>';
echo '<intro_len>'.strlen($intro).'</intro_len>';
if (1 > strlen($essay_comment)){
$essay_comment = ' ';
} else {
$essay_comment = urlencode($essay_comment);
}
if (1 > strlen($essay_grade)) {
$essay_grade = ' ';
}
if (2 < strlen($topic)){
$topic = urlencode($topic);
} else {
$topic = ' ';
}
if (2 < strlen($intro)){
$intro = urlencode($intro);
} else {
$intro = ' ';
}
if (2 < strlen($support)){
$support = urlencode($support);
} else {
$support = ' ';
}
if (2 < strlen($conclusion)){
$conclusion = urlencode($conclusion);
} else {
$conclusion = ' ';
}
echo '<setTopic>'.$setTopic.'</setTopic>';
echo '<essay_active>'.$essay_active.'</essay_active>';
echo '<essay_date>'.$essay_date.'</essay_date>';
echo '<essayID>'.$essayID.'</essayID>';
echo '<topic>'.$topic.'</topic>';
echo '<intro>'.$intro.'</intro>';
echo '<support>'.$support.'</support>';
echo '<conclusion>'.$conclusion.'</conclusion>';
echo '<essay_comment>'.$essay_comment.'</essay_comment>';
echo '<submitted>'.$submitted.'</submitted>';
echo '<dateSubmitted>'.$dateSubmitted.'</dateSubmitted>';
echo '<essay_grade>'.$essay_grade.'</essay_grade>';
echo '<AdStudentEssayID>'.$AdStudentEssayID.'</AdStudentEssayID>';
}
} else {
The output I get from this is:
'Test Introduction Paragraph
Test Supporting Paragraph
2nd test supporting paragraph
Test Conclusion Paragraph
Test Essay Topic
<intro1>1</intro1>
<intro_len>1</intro_len>
<setTopic>%3Cp%3ETest%20Topic%3C%2Fp%3E</setTopic>
<essay_active>1</essay_active>
<essay_date>01-01-70</essay_date>
<essayID>29</essayID>
<topic></topic>
<intro></intro>
<support></support>
<conclusion></conclusion>
<essay_comment>1</essay_comment>
<submitted>1</submitted>
<dateSubmitted>07-11-16</dateSubmitted>
<essay_grade></essay_grade>
<AdStudentEssayID>59</AdStudentEssayID>'
The output I expect is:
'<intro1>Test Introduction Paragraph</intro1>
<intro_len>1</intro_len>
<setTopic>%3Cp%3ETest%20Topic%3C%2Fp%3E</setTopic>
<essay_active>1</essay_active>
<essay_date>01-01-70</essay_date>
<essayID>29</essayID>
<topic>Test Essay Topic</topic>
<intro>Test Introduction Paragraph</intro>
<support>Test Supporting Paragraph 2nd test supporting paragraph</support>
<conclusion>Test Conclusion Paragraph</conclusion>
<essay_comment>1</essay_comment>
<submitted>1</submitted>
<dateSubmitted>07-11-16</dateSubmitted>
<essay_grade></essay_grade>
<AdStudentEssayID>59</AdStudentEssayID>'
So the question is, Why is it doing this? Why does it output 'intro','support','conclusion', and 'topic' instead of saving them to the variable?

Calling a php variable that is within an if

Can someone explain me why I cannot call a var that is set inside an if? And how to call it? I don't understand why this come empty.
I need the vars $workshop_manha and $workshop_tarde bring the values that comes from the DB.
CODE
$id = implode(",", $id);
$sql_consulta = mysql_query("SELECT * FROM pessoa WHERE id IN($id)")
or die (mysql_error());
$linha = mysql_fetch_array($sql_consulta);
$id = $linha['id'];
$nome = $linha['nome'];
$opcoes = $linha['opcoes'];
$opcoes2 = explode(":", $opcoes);
$opcoes3 = explode("+", $opcoes2[1]);
$opcao_congresso = $opcoes3[0]; // Option Congress
if(!empty($opcoes2[2])){
$opcoes4 = explode("+", $opcoes2[2]);
$pre_workshop_manha = $opcoes4[0]; // Workshop Morning Option
if($pre_workshop_manha == 'Paul Gilbert'){
$workshop_manha = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
}
if($pre_workshop_manha == 'Daniel Rijo'){
$workshop_manha = "Daniel Rijo: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
if($pre_workshop_manha == 'Maria Salvador'){
$workshop_manha = "Maria do Céu Salvador: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
}
if(!empty($opcoes2[3])){
$opcoes5 = explode("+", $opcoes2[3]);
$pre_workshop_tarde = $opcoes5[0]; // Worhshop Afternoon Option
if($pre_workshop_tarde == 'Donna Sudak'){
$workshop_tarde = "Donna Sudak: Quando as coisas ficam difíceis: Aplicações práticas da Terapia Comportamental Dialética";
}
if($pre_workshop_tarde == 'Philipp Kendall'){
$workshop_tarde = "Philipp Kendall: Estratégias dentro de tratamentos empiricamente baseados em evidências para jovens com ansiedade";
}
}
echo "Work manhã: ".$workshop_manha; //is coming empty :(
echo "Work tarde: ".$workshop_tarde; //is coming empty :(
That's because $workshop_manha and $workshop_tarde are not defined before the if statement.
Put this before the if statement:
$workshop_manha = '';
$workshop_tarde = '';
You can use them as an array().
Empty the values at the beginning :
$workshop_manha=array();
$workshop_tarde=array();
Than use the values as :
$workshop_manha[] = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
Display them as below :
if(!empty($workshop_manha)) {
foreach ($workshop_manha as $manha) {
echo "$manha <br />";
}
}
if(!empty($workshop_tarde)) {
foreach ($workshop_tarde as $tarde) {
echo "$tarde <br />";
}
}

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.

Extract body text from Email PHP

I am currently using an imap stream to get emails from an inbox.
Everything is working fine except I am unsure how to get the body text and title of the email. If I do imap_body($connection,$message) the base 64 equivalent of the email attachment is included in the text.
I am currently using this function to get the attachments.
http://www.electrictoolbox.com/function-extract-email-attachments-php-imap/
Well php imap's function are not fun to work with. A user on this page explains the inconsistencies with getting emails: http://php.net/manual/en/function.imap-fetchbody.php#89002
Using his helpful information I created a reliably way to get an email's body text.
$bodyText = imap_fetchbody($connection,$emailnumber,1.2);
if(!strlen($bodyText)>0){
$bodyText = imap_fetchbody($connection,$emailnumber,1);
}
$subject = imap_headerinfo($connection,$i);
$subject = $subject->subject;
echo $subject."\n".$bodyText;
My solution (works with all types and charset) :
function format_html($str) {
// Convertit tous les caractères éligibles en entités HTML en convertissant les codes ASCII 10 en $lf
$str = htmlentities($str, ENT_COMPAT, "UTF-8");
$str = str_replace(chr(10), "<br>", $str);
return $str;
}
// Start
$obj_structure = imap_fetchstructure($imapLink, $obj_mail->msgno);
// Recherche de la section contenant le corps du message et extraction du contenu
$obj_section = $obj_structure;
$section = "1";
for ($i = 0 ; $i < 10 ; $i++) {
if ($obj_section->type == 0) {
break;
} else {
$obj_section = $obj_section->parts[0];
$section.= ($i > 0 ? ".1" : "");
}
}
$text = imap_fetchbody($imapLink, $obj_mail->msgno, $section);
// Décodage éventuel
if ($obj_section->encoding == 3) {
$text = imap_base64($text);
} else if ($obj_section->encoding == 4) {
$text = imap_qprint($text);
}
// Encodage éventuel
foreach ($obj_section->parameters as $obj_param) {
if (($obj_param->attribute == "charset") && (mb_strtoupper($obj_param->value) != "UTF-8")) {
$text = utf8_encode($text);
break;
}
}
// End
print format_html($text);
You Can also try these
content-type:text/html
$message = imap_fetchbody($inbox,$email_number, 2);
content-type:plaintext/text
$message = imap_fetchbody($inbox,$email_number, 1);

Categories