I need to write a code that allows me to send an specific link within an array. This is a short idea of what I'm trying to do. Depending on the country code I'll send a brochure in the specific language. I also want to know if I can do it by switch...
This is the code I got so far...
<?php
$de_brochure = ('https://ruta/de-brochure.pdf');
$en_brochure = ('https://ruta/en-brochure.pdf');
$es_brochure = ('https://ruta/es-brochure.pdf');
$country_code = 'ES'; // Normally I get this code from a form.
$brochure = array ( $de_brochure, $en_brochure, $es_brochure );
$brochure_link = '';
if ( $country_code == 'ES' ) {
$to = 'info#kazzabe.com.es';
$subject = 'Ejemplo';
$txt = 'El dossier a enviar es' . $brochure_link[$brochure];
$headers = 'De: sample#sample.com' . '\r\n' .
'CC: anothersample#sample.com';
mail ($to, $subject, $txt, $headers );
} else {
echo $country_code . 'no es el código de españa';
}
When I run my code, this is the output I GET:
WARNING Illegal offset type on line number 17
NOTICE Uninitialized string offset: 1 on line number 17
You make your array and a unused "link" variable
$brochure = array ( $de_brochure, $en_brochure, $es_brochure );
$brochure_link = '';
And then access this link variable instead of the array:
$txt = 'El dossier a enviar es' . $brochure_link[$brochure];
^^^^^^^^^^^^^^^^^^^^^^^^^
This is where it fails. Using an array with named keys (a.k.a. hash) would make it easier:
$brochures = [
'DE' => 'https://ruta/de-brochure.pdf',
'EN' => 'https://ruta/en-brochure.pdf',
'ES' => 'https://ruta/es-brochure.pdf'
];
$country_code = 'ES';
# ...
$txt = 'El dossier a enviar es' . $brochures[$country_code];
do something like this
$brochure_link_arr= array(
"DE"=>'https://ruta/de-brochure.pdf',
"EN" =>'https://ruta/en-brochure.pdf',
"ES"=> 'https://ruta/es-brochure.pdf'
);
if ( $country_code == 'ES' ) {
..
$txt = 'El dossier a enviar es' . $brochure_link_arr[$country_code];
Related
I am trying to use my localhost to connect to another server remotely and execute a mail function so i use get method to send the email and the subject
here is my localhost file :
<?php
for ($email=0; $email< $n_emails; $email++){
$urlsmtp = $link.'?email='.$destino.'&subject='.$tornado.'&msg='.$msgrand.'&name='.$_POST['naming'].'&from='.$_POST['localting'];
//this link is something like http://test.com/RemoteSmpt.php?email=test#mail.com &subject=test&msg=test&name=test&from=test
$urlsmtp = str_replace(" ", "%20", $urlsmtp);
$response = file_get_contents($urlsmtp);
}
?>
and the file RemoteSmpt.php which i will put it in the server contains this code :
<?php
if ( isset( $_GET['email']) && $_GET['subject'] && $_GET['msg'] && $_GET['name'] && $_GET['from']) {
$email = $_GET['email'];
$subject = $_GET['subject'];
$msg = $_GET['msg'];
$name = $_GET['name'];
$from = $_GET['from'];
$headers = 'From: '.$name.'<'.$from.'>\n';
$enviar = mail($email, $subject, $msg, $headers);
if ($enviar){
echo ('<font color="green"> -'. $email .' 0k -- With Subject : '.$subject.'</font><br>');
} else {
echo ('<font color="red"> -'. $email .' Not Sended -- With Subject : '.$subject.'</font><br>');
}
}else
{echo 'Invalid Data !<br>';}
?>
so after i upload the RemoteSmpt.php file and try this is what i got :
Warning: file_get_contents(http://...#mail.com&subject=tset&msg=test&name=test&from=test): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in Mylocalhost file !
Please any idea how to fix this code !
You need to properly encode special characters in the URL parameters, which can be done using urlencode().
You can use the http_build_query() function to build a query string from an associative array, and properly encode everything.
$params = http_build_query([
'email' => $destino,
'subject' => $tornado,
'msg' => $msgrand,
'name' => $_POST['naming'],
'from' => $_POST['localting']
]);
$urlsmtp = $link . '?' . $params;
I´m forking this repo https://github.com/FundacionPesetacoin/Pesetacoin_WooCommerce-Plugin and working fine. But when change the API for catch the price in other Site, not update
I try some differents links of API and make same.
Original code get info of his private API, and I want use other public API.
With original code, API show this info:
{"status" : "success" , "message" : "null", "ptc_btc" : "0.00000083", "btc_usd" : "5070.29", "btc_eur" : "4505.46", "supply" : "138188628.56442260", "ptc_eur" : "0.00373953", "ptc_usd" : "0.00420834" , "date" : "2019-04-13 10:20:07"}
and get "ptc_eur" of API for shows in shoppping cart.
Now I want use the new API of other site https://api.coingecko.com/api/v3/simple/price?ids=reecore&vs_currencies=eur than shows this info:
{"reecore":{"eur":0.0046564}}
I want use only the "eur" data , same the original code use the "ptc_eur" but dont work.
Sorry for my english.
ORIGINAL CODE:
//precio en PesetaCoins
global $woocommerce;
$euros= $woocommerce->cart->total;
$xaxa= "http://nodos.pesetacoin.info/api/api.php";
$data = file_get_contents($xaxa);
$pesetas = json_decode($data, true);
$valor_ptc= $pesetas['ptc_eur'];
$ptc= $euros/$valor_ptc;
$ptc= round($ptc, 2);
//precio en PesetaCoins
$pagos= array();
$metodo= $order->get_payment_method();
$i = -1;
foreach ( $this->account_details as $account ) {
$i++;
$pagos[$i]=
$pagos[$i]= esc_attr( wp_unslash( $account['hash_name'] ) );
}
$cont= rand(0, $i);
if($metodo == "ptc") {
$description= "<span style='font-size:14px'>Para completar el pedido, debe enviar la cantidad <b>".$ptc."</b> de Pesetacoin a la siguiente dirección: <b>";
$description.= $pagos[$cont];
$description.="</b><br>Una vez se reciba la transacción se enviará el pedido.</span>";
echo wpautop(wptexturize($description));
}
}
NEW CODE:
//precio en ReecoreCoins
global $woocommerce;
$euros= $woocommerce->cart->total;
$xaxa= "https://api.coingecko.com/api/v3/simple/price?ids=reecore&vs_currencies=eur";
$data = file_get_contents($xaxa);
$pesetas = json_decode($data, true);
$valor_reex= $pesetas['eur'];
$reex= $euros/$valor_reex;
$reex= round($reex, 2);
//precio en ReecoreCoins
$pagos= array();
$metodo= $order->get_payment_method();
$i = -1;
foreach ( $this->account_details as $account ) {
$i++;
$pagos[$i]=
$pagos[$i]= esc_attr( wp_unslash( $account['hash_name'] ) );
}
$cont= rand(0, $i);
if($metodo == "reex") {
$description= "<span style='font-size:14px'>Para completar el pedido, debe enviar la cantidad <b>".$reex."</b> de Reecorecoin a la siguiente dirección: <b>";
$description.= $pagos[$cont];
$description.="</b><br>Una vez se reciba la transacción se enviará el pedido.</span>";
echo wpautop(wptexturize($description));
}
}
It's because the now Coingecko API return a nested JSON which is simply a JSON file with a fairly big portion of its values being other JSON objects.
Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.
Using Phrase, keys will be stored by separating levels with a dot.
The new API returns a nested JSON object, where you need two steps to access the desired value:
$valor_reex= $pesetas['reecore']['eur'];
You might want to use ready library for this. Like this one https://github.com/npabisz/coingecko-api.
Install via composer:
composer require npabisz/coingecko-api
And then get your reecore price by:
$client = new \CoinGecko\Client();
$data = $client->Simple->Price->get([
'ids' => 'reecore',
'vs_currencies' => 'eur',
]);
$reecorePrice = $data['reecore']['eur'] ?? null;
I try to get the image that is stored in a folder of my localhost, I do not understand what is the problem, the attribute in JSON IMAGEN get empty,
I need to convert it here..
<?php
/**
* Obtiene todas las metas de la base de datos
*/
const ESTADO = "estado";
const DATOS = "negocios";
const MENSAJE = "mensaje";
const CODIGO_EXITO = 1;
const CODIGO_FALLO = 2;
require '../data/Gastos.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
// Manejar petición GET
$negocios = Gastos::getAllNegocios();
//Definir el tipo de la respuesta
header('Content-Type: application/json');
$imagesPath = '/localhost:8888/htdocs/';
if ($negocios) {
$datos[ESTADO] = CODIGO_EXITO;
foreach($negocios as $meta) {
// Push an entry in the new array, replacing raw image with base64-encoded
$imgFileContents = file_get_contents($imagesPath.'/'.$meta['IMAGEN']);
$datos["negocios"][] = array(
'IDNEGOCIO' => $meta['IDNEGOCIO'],
'NOMBREIMAGEN' => $meta['NOMBREIMAGEN'],
'IMAGEN' => base64_encode($imgFileContents),
'NOMBRENEGOCIO' => $meta['NOMBRENEGOCIO'],
'DESCRIPCION' => $meta['DESCRIPCION'],
);
}
print json_encode($datos,JSON_UNESCAPED_UNICODE);
} else {
print json_encode(array(
ESTADO => CODIGO_FALLO,
MENSAJE => "Ha ocurrido un error"
));
}
}
?>
Get empty in JSON
{"estado":1,"negocios":[{"IDNEGOCIO":"1","NOMBREIMAGEN":"img_1","IMAGEN":"","NOMBRENEGOCIO":"YARYAS","DESCRIPCION":"Descripcion1"},{"IDNEGOCIO":"2","NOMBREIMAGEN":"img_2","IMAGEN":"","NOMBRENEGOCIO":"Skizza","DESCRIPCION":"Descripcion2"}]}
It is the directoy
I think it might be because you're $imagesPath URL is pointing to a directory incorrectly. In most localhost setups "htdocs" is already the default directory when travelling to the localhost server, so assuming its a relative URL it should be something like "http://localhost:8888/fotos/" not "http://localhost:8888/htdocs/fotos/".
Try:
$imagesPath = 'http://localhost:8888/';
i have the following function:
public function getMails()
{
$mails = array();
$numMessages = imap_num_msg($this->imap);
for ($i = 1; $i <= $numMessages; $i++)
{
$header = imap_header($this->imap, $i);
$fromInfo = $header->from[0];
$replyInfo = $header->reply_to[0];
$details = array(
"fromAddr" => (isset($fromInfo->mailbox) && isset($fromInfo->host))
? $fromInfo->mailbox . "#" . $fromInfo->host : "",
"fromName" => (isset($fromInfo->personal))
? $fromInfo->personal : "",
"replyAddr" => (isset($replyInfo->mailbox) && isset($replyInfo->host))
? $replyInfo->mailbox . "#" . $replyInfo->host : "",
"replyName" => (isset($replyInfo->personal))
? $replyInfo->personal : "",
"subject" => (isset($header->subject))
? $header->subject : "",
"udate" => (isset($header->udate))
? $header->udate : ""
);
$bodyText = imap_fetchbody($this->imap,$i,1.2);
if(!strlen($bodyText)>0){
$bodyText = imap_fetchbody($this->imap,$i,1);
}
$details['body'] = $bodyText;
$uid = imap_uid($this->imap, $i);
$current_mail = array('header'=>$header, 'from'=>$fromInfo, 'reply'=>$replyInfo, 'details'=>$details);
$mails[$i] = $current_mail;
}
}
However there is a problem with the body text.
This is a test mail that i sendt from my email that looks like this:
Hello world
Med venlig hilsen
Marc Rasmussen
Besøg mig på MarcRasmussen.dk
However the body text is looks like this when taken from imap:
Hello world=0A=
=0A=
Med venlig hilsen=0A=
=0A=
Marc Rasmussen=0A=
=0A=
Bes=F8g mig p=E5 MarcRasmussen.dk =
is there any buildin method in PHP to fix this issue?
You have to check the Content-Transfer-Encoding header of the MIME part you are working on (hint: it's available in IMAP's BODYSTRUCTURE) and decode it yourself. The two most common encoding are quoted-printable and base64. See RFC 2045, chapter 6 for details.
You could try to use the $options parameter of the imap_fetchbody function. Maybe with flag FT_INTERNAL combined with utf8_encode:
$bodyText = utf8_encode(imap_fetchbody($this->imap,$i,1, FT_INTERNAL));
I hope it works for you!
I'm using a webservice in php here :
http://cdt33.tourinsoft.com/soft/RechercheDynamique/Syndication/controle/syndication2.asmx
You can test for example getListing with idModule = dafda774-317d-4b5f-bb8b-33e5977dc13c, and click on invoke
I'm trying to retrieve this result (XML) in php. But i have no idea how to do this.
If i use getListing like :
$client = new SoapClient("http://cdt33.tourinsoft.com/soft/RechercheDynamique/Syndication/controle/syndication2.asmx?wsdl");
echo "GET LISTING";
$getListing = $client->getListing(
array (
'idModule' => "dafda774-317d-4b5f-bb8b-33e5977dc13c"));
echo("<pre>");
print_r($getListing);
echo("</pre>");
Result is something like that :
stdClass Object
(
[getListingResult] => stdClass Object
(
[schema] =>
[any] =>
HOTAQU03301V3EZB2005-06-29T00:00:00.0000000+02:002012-06-28T14:43:44.0000000+02:0074HOTHôtellerie1e9eb500-e0c9-4a53-b6a5-0b36faa63ed4true 2 étoiles Français www.hotel-lenovel.com +33 5 57 52 26 47 7 oui En centre ville$ Au bord de la mer Ascenseur$ Salon 22 -1.164866 Au coeur d'Arcachon, à deux pas de la gare, du théâtre de l'Olympia et de l'Office du Tourisme, le Novel bénéficie d'une situation privilégiée. Les chambres sont chaleureuses et douillettes pour un séjour....... ETC
How can i retieve XML ?? Thanks you !
Here is sometihng to try out, run it and check the source code for the page, it should contain the xml file. SOAP is just a fancy way of doing a post.
<?php
function smartpost($type,$host,$port='80',$path='/',$data='') {
$d="";
$str="";
$_err = 'lib sockets::'.__FUNCTION__.'(): ';
switch($type) { case 'http': $type = ''; case 'ssl': continue; default: die($_err.'bad $type'); } if(!ctype_digit($port)) die($_err.'bad port');
if(!empty($data)) foreach($data AS $k => $v) $str .= urlencode($k).'='.urlencode($v).'&'; $str = substr($str,0,-1);
$fp = fsockopen($host,$port,$errno,$errstr,$timeout=30);
if(!$fp) die($_err.$errstr.$errno); else {
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($str)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $str."\r\n\r\n");
while(!feof($fp)) $d .= fgets($fp,4096);
fclose($fp);
$result = explode("\r\n\r\n", $d, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
} return array($header, $content);
}
list($header, $content) = smartpost('http','cdt33.tourinsoft.com','80','/soft/RechercheDynamique/Syndication/controle/syndication2.asmx/getListingByIDs',array('idModule'=>'dafda774-317d-4b5f-bb8b-33e5977dc13c','ObjetTourCode' => '','IDs' => ''));
print($content);
?>
assuming you are using standard PHP SoapClient, try using
$client->__getLastRequestHeaders()
(http://www.php.net/manual/en/soapclient.getlastresponse.php)
According to maual, you should also set trace option to true on SoapClient:
$client = new SoapClient("http://cdt33.tourinsoft.com/soft/RechercheDynamique/Syndication/controle/syndication2.asmx?wsdl", array('trace' => true));
Regards, Jakub Derda
class ABRSoapClient extends SoapClient
{
$result = "";
function __doRequest($request, $location, $action, $version)
{
$result = parent::__doRequest($request, $location, $action, $version);
return $result;
}
}
Instead of creating object of SoapClient, Create object of ABRSoapClient, Here $result is your XML string from Web-Service.
You can access that variable using $client->result;