I created a wordpress plugin to retrieve the information of a token on pancakeswap. I don't understand why it doesn't show me the data. if someone can look at my code and tell me what's wrong that will be super nice. thank you in advance.
<?php
/*
Plugin name: WP PancakeSwap
Description: Ce plugin nous permet de dialoguer avec l' api PancakeSwap
Author: Jean Philippe Faucon
Version : 1.0
*/
/* Copyright 2021 Jean Philippe Faucon (email : jpfaucon81#hotmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Utilisation de l'API Pancakeswap.
// https://github.com/pancakeswap/pancake-info-api/blob/develop/v2-documentation.md
// Source : https://api.pancakeswap.info/api/v2/tokens/0xdb72feadd4a0734d62fa5a078551986519dca19d
// 1 étape : récupérer les infos auprès de PancakeSwap
function _get_wp_pancakeswap_datas () {
$args = array (
'timeout' => 120,
'httpversion' => '1.1'
);
$url = "https://api.pancakeswap.info/api/v2/tokens/0xdb72feadd4a0734d62fa5a078551986519dca19d";
$call = wp_remote_get($url, $args);
$response = wp_remote_retrieve_body($call);
return $response;
}
// 2 étape : mettre en forme les données
add_shortcode('pancakeswap','output_pancakeswap');
function output_pancakeswap() {
$datas = _get_wp_pancakeswap_datas () ;
//Nom et prix du token
$output = 'Nom du token : '.$datas->name;
$output .= '<br>';
$output .= 'Valeur du token : '.$datas->price;
$output .= ' $';
$output .= '<br>';
$output .= 'Valeur du token en BNB : '.$datas->price_BNB;
return $output;
}
First of all you have to json decode the response.
If this function return the body json decoded as the name suggest wp_remote_retrieve_body($call);
try to "return $response->data" in the function _get_wp_pancakeswap_datas ()
{"updated_at":1636744974029,"data":{"name":"Alfcoin","symbol":"ALF","price":"0.1937757238779150782534763119032","price_BNB":"0.000314980409577114948657924847012"}}
If not you have to do something like this in the function _get_wp_pancakeswap_datas()
$response = json_decode(wp_remote_retrieve_body($call));
return $response->data;
This is essentially right out of the Wordpress manual.
You need to convert the json response to a php object.
You need to access the embedded object from the json response
Alternatively, you could opt for the json_decode() 2nd parameter that returns a php array instead of a php object.
function _get_wp_pancakeswap_datas () {
$args = array (
'timeout' => 120,
'httpversion' => '1.1'
);
$url = "https://api.pancakeswap.info/api/v2/tokens/0xdb72feadd4a0734d62fa5a078551986519dca19d";
$call = wp_remote_get($url, $args);
$response = json_decode(wp_remote_retrieve_body($call));
return $response;
}
add_shortcode('pancakeswap','output_pancakeswap');
function output_pancakeswap() {
$response = _get_wp_pancakeswap_datas();
//Nom et prix du token
$datas = $response->data;
$updateAt = $response->updated_at;
$output = 'Nom du token : '.$datas->name;
$output .= '<br>';
$output .= 'Valeur du token : '.$datas->price;
$output .= ' $';
$output .= '<br>';
$output .= 'Valeur du token en BNB : '.$datas->price_BNB;
return $output;
}
Related
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'm struggling trying to remove the scaped characters from the json response in my CodeIgniter with PhilSturgeon REST Server.
Everything is working OK, but the problem comes with the response, when I access the URL to get the data in json format I get it, but with escaped characters.
Example:
http://localhost/revista_servidor/index.php/api/notas/nota/id/1
Gives me the next response:
[{"id":"1","autor":"Prueba autor","titulo":"Comprobaci\u00f3n de t\u00ed\u00edtulo.","subtitulo":"Comprobaci\u00f3n de subt\u00edtulo.","foto1":"http://link.a.foto/foto1","texto1":"Comprobaci\u00f3n de texto 1.\r\n","pauta1":"1","texto2":"Comprobaci\u00f3n de texto 2.\r\n","foto2":"http://link.a.foto/foto2","pauta2":"1","texto3":"Comprobaci\u00f3n de texto 3.","foto3":"http://link.a.foto/foto3","pauta3":"1","texto4":"Comprobaci\u00f3n de texto 4.","texto5":"Comprobaci\u00f3n de texto 5.","texto6":"Comprobaci\u00f3n de texto 6.","datosweb":"http://link.a.pagina.de.datos/","adelanto":"Comprobaci\u00f3n del texto de adelante","nrorevista":"69"}]
It escapes URLs adding a backslash \ and changing specials characters (ó in this example) with: \u00f3.
I've tried adding stripslashes()but didn't work.
I checked the response in developers tools and it comes as expected: Content-Type: application/json.
How can I fix this encoding problem? I've also checked the configuration files and there seems to be nothing to change for this issue.
I hope someone can point me in the right direction, below is my code:
Controller: /application/controllers/api/notas.php
function nota_get() {
// ID verification.
if ( !$this->get('id') ) {
// NO ID.
$this->response(NULL, 400);
}
$nota = $this->Notas_model->get( $this->get('id') );
if ($nota) {
stripcslashes($this->response($nota, 200));
}
else {
$this->response(NULL, 404);
}
}
Model: /application/models/notas_model.php
function get($id = 0) {
$this->load->database();
if ( $id ) {
$query = $this->db->get_where( 'notas', array('id' => $id) );
}
else {
$query = $this->db->get('notas');
}
return $query->result();
}
I don't know if this matters, but this data will be accessed via javascript in the client side.
Thanks in advance!
Its just the way JSON works, try json_decode function.
e.g:
$json = json_decode($json_string);
$json->autor;
1) You need to be using json_decode() and then urldecode(), instead of stripslashes()
2) Both urldecode() and stripslashes() take a string as an argument, while you are trying to feed into it an object -- which gets "autoreduced" into something that depends on the PHP version... Whatever it is, it's probably not what you are expecting.
In your code:
if ($nota) {
stripcslashes($this->response($nota, 200));
}
you'll need a) save the result of decoding to the same or another variable, b) to loop through your object ( $nota ) and unescape the value in each key-value pair.
Try
...
$cleanObject = array();
if ($nota) {
$decodedObject = json_decode($this->response($nota, 200));
foreach ( $decodedObject as $key => $value ) {
$cleanObject[$key] = urldecode( $value );
}
}
echo "<pre>";
print_r($cleanedObject);
echo "</pre>";
// output
/*
Array
(
[id] => 1
[autor] => Prueba autor
[titulo] => Comprobación de tíítulo.
[subtitulo] => Comprobación de subtítulo.
[foto1] => http://link.a.foto/foto1
[texto1] => Comprobación de texto 1.
[pauta1] => 1
[texto2] => Comprobación de texto 2.
[foto2] => http://link.a.foto/foto2
[pauta2] => 1
[texto3] => Comprobación de texto 3.
[foto3] => http://link.a.foto/foto3
[pauta3] => 1
[texto4] => Comprobación de texto 4.
[texto5] => Comprobación de texto 5.
[texto6] => Comprobación de texto 6.
[datosweb] => http://link.a.pagina.de.datos/
[adelanto] => Comprobación del texto de adelante
[nrorevista] => 69
)
*/
...
Hopefully, this is what you are looking to achieve.
Depending on your further needs, you may have to re-encode the result. Based on javascript you mention, you may then need to convert the result back to JSON:
$unescapedAndJSONencodedObject = json_encode( $cleanObject );
I'll try to present it as simple as I can:
I use json_encode() to encode a number of utf-8 strings from different languages and I notice that characters remain unchanged when they belong to ASCII table but everything else is returned as '\unnnn', where 'nnnn' a hexadecimal number.
See the code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<title>Multibyte string functions</title>
</head>
<body>
<h3>Multibyte string functions</h3>
<p>
<?php
//present json encode errors nicely:
//assign integer values to keys and error names to values
echo '<br /><b>Define JSON errors</b><br />';
$constants = get_defined_constants(true);
$json_errors = array();
foreach ($constants["json"] as $name => $value) {
if (!strncmp($name, "JSON_ERROR_", 11)) {
$json_errors[$value] = $name;
}
}
echo nl2br(print_r($json_errors, true), true);
//Display current detection order
echo "<br /><b>Current detection order 'mb_detect_order()':</b> ", implode(", ", mb_detect_order());
//Display internal encoding
echo "<br /><b>Internal encoding 'mb_internal_encoding()':</b> ", mb_internal_encoding();
//Get current language
echo "<br /><b>Current detection language 'mb_language()' ('neutral' for utf8):</b> ", mb_language();
//our test data
//a nowdoc that can break a <input> field;
$str = <<<'STR'
O'Reilly(\n) "& 'Big\Two # <span>bo\tld</span>"
STR;
$strings = array(
$str,
"Latin: tell me the answer and I might find the question!",
"Greek: πες μου την ερώτηση και ίσως βρω την απάντηση!",
"Chinese simplified: 告诉我答复,并且我也许发现问题!",
"Arabic: أخبرني الاجابة, انا قد تجد مسالة!",
"Portuguese: mais coisas a pensar sobre diário ou dois!",
"French: plus de choses à penser à journalier ou à deux!",
"Spanish: ¡más cosas a pensar en diario o dos!",
"Italian: più cose da pensare circa giornaliere o due!",
"Danish: flere ting å tenke på hver dag eller to!",
"Chech: Další věcí, přemýšlet o každý den nebo dva!",
"German: mehr über Spaß spät schönen",
"Albanian: më vonë gjatë fun bukur",
"Hungarian: több mint szórakozás késő csodálatos kenyér"
);
//show encoding and then encode
foreach( $strings as $string ){
echo "<br /><br />$string :", mb_detect_encoding($string);
$json = json_encode($string);
echo "<br />Error? ", $json_errors[json_last_error()];
echo '<br />json=', $json;
}
The above code will output:
Define JSON errors
Array
(
[0] => JSON_ERROR_NONE
[1] => JSON_ERROR_DEPTH
[2] => JSON_ERROR_STATE_MISMATCH
[3] => JSON_ERROR_CTRL_CHAR
[4] => JSON_ERROR_SYNTAX
[5] => JSON_ERROR_UTF8
)
Current detection order 'mb_detect_order()': ASCII, UTF-8
Internal encoding 'mb_internal_encoding()': ISO-8859-1
Current detection language 'mb_language()' ('neutral' for utf8): neutral
O'Reilly(\n) "& 'Big\Two # bo\tld" :ASCII
Error? JSON_ERROR_NONE
json="O'Reilly(\\n) \"& 'Big\\Two # bo\\tld<\/span>\""
Latin: tell me the answer and I might find the question! :ASCII
Error? JSON_ERROR_NONE
json="Latin: tell me the answer and I might find the question!"
Greek: πες μου την ερώτηση και ίσως βρω την απάντηση! :UTF-8
Error? JSON_ERROR_NONE
json="Greek: \u03c0\u03b5\u03c2 \u03bc\u03bf\u03c5 \u03c4\u03b7\u03bd \u03b5\u03c1\u03ce\u03c4\u03b7\u03c3\u03b7 \u03ba\u03b1\u03b9 \u03af\u03c3\u03c9\u03c2 \u03b2\u03c1\u03c9 \u03c4\u03b7\u03bd \u03b1\u03c0\u03ac\u03bd\u03c4\u03b7\u03c3\u03b7!"
Chinese simplified: 告诉我答复,并且我也许发现问题! :UTF-8
Error? JSON_ERROR_NONE
json="Chinese simplified: \u544a\u8bc9\u6211\u7b54\u590d\uff0c\u5e76\u4e14\u6211\u4e5f\u8bb8\u53d1\u73b0\u95ee\u9898!"
Arabic: أخبرني الاجابة, انا قد تجد مسالة! :UTF-8
Error? JSON_ERROR_NONE
json="Arabic: \u0623\u062e\u0628\u0631\u0646\u064a \u0627\u0644\u0627\u062c\u0627\u0628\u0629, \u0627\u0646\u0627 \u0642\u062f \u062a\u062c\u062f \u0645\u0633\u0627\u0644\u0629!"
Portuguese: mais coisas a pensar sobre diário ou dois! :UTF-8
Error? JSON_ERROR_NONE
json="Portuguese: mais coisas a pensar sobre di\u00e1rio ou dois!"
French: plus de choses à penser à journalier ou à deux! :UTF-8
Error? JSON_ERROR_NONE
json="French: plus de choses \u00e0 penser \u00e0 journalier ou \u00e0 deux!"
Spanish: ¡más cosas a pensar en diario o dos! :UTF-8
Error? JSON_ERROR_NONE
json="Spanish: \u00a1m\u00e1s cosas a pensar en diario o dos!"
Italian: più cose da pensare circa giornaliere o due! :UTF-8
Error? JSON_ERROR_NONE
json="Italian: pi\u00f9 cose da pensare circa giornaliere o due!"
Danish: flere ting å tenke på hver dag eller to! :UTF-8
Error? JSON_ERROR_NONE
json="Danish: flere ting \u00e5 tenke p\u00e5 hver dag eller to!"
Chech: Další věcí, přemýšlet o každý den nebo dva! :UTF-8
Error? JSON_ERROR_NONE
json="Chech: Dal\u0161\u00ed v\u011bc\u00ed, p\u0159em\u00fd\u0161let o ka\u017ed\u00fd den nebo dva!"
German: mehr über Spaß spät schönen :UTF-8
Error? JSON_ERROR_NONE
json="German: mehr \u00fcber Spa\u00df sp\u00e4t sch\u00f6nen"
Albanian: më vonë gjatë fun bukur :UTF-8
Error? JSON_ERROR_NONE
json="Albanian: m\u00eb von\u00eb gjat\u00eb fun bukur"
Hungarian: több mint szórakozás késő csodálatos kenyér :UTF-8
Error? JSON_ERROR_NONE
json="Hungarian: t\u00f6bb mint sz\u00f3rakoz\u00e1s k\u00e9s\u0151 csod\u00e1latos keny\u00e9r"
As you can see in most languages-except English-there is a hexadecimal conversion of utf-8 characters.
Is it possible to encode by not replacing my unicode characters? Is it safe? What other people do?
You should consider such encodings that are coming from user input in pages and stored to mysql.
Thanks.
Maybe you should try json_encode($string, JSON_UNESCAPED_UNICODE) , or any method in http://php.net/manual/fr/function.json-encode.php that may be usefull for your various cases.
Ok,
really thanks for the answer!
The problem is that I'm on version PHP Version 5.3.10 and json_encode($string, JSON_UNESCAPED_UNICODE) isn't an option.
Fortunately, a guy called "Mr Swordsteel" posted a comment at php's manual http://www.php.net/manual/en/function.json-encode.php which actually does the trick (thank you Mr Swordsteel!)
The real paradox is that it emulates completely json_encode function and gives a hint if we want to port it to another language like javascript and keep our libraries communicative.
function my_json_encode($in){
$_escape = function ($str) {
return addcslashes($str, "\v\t\n\r\f\"\\/");
};
$out = "";
if (is_object($in)){
$class_vars = get_object_vars(($in));
$arr = array();
foreach ($class_vars as $key => $val){
$arr[$key] = "\"{$_escape($key)}\":\"{$val}\"";
}
$val = implode(',', $arr);
$out .= "{{$val}}";
}elseif (is_array($in)){
$obj = false;
$arr = array();
foreach($in as $key => $val){
if(!is_numeric($key)){
$obj = true;
}
$arr[$key] = my_json_encode($val);
}
if($obj){
foreach($arr AS $key => $val){
$arr[$key] = "\"{$_escape($key)}\":{$val}";
}
$val = implode(',', $arr);
$out .= "{{$val}}";
}else {
$val = implode(',', $arr);
$out .= "[{$val}]";
}
}elseif (is_bool($in)){
$out .= $in ? 'true' : 'false';
}elseif (is_null($in)){
$out .= 'null';
}elseif (is_string($in)){
$out .= "\"{$_escape($in)}\"";debug('in='.$in.', $_escape($in)='.$_escape($in).', out='.$out);
}else{
$out .= $in;
}
return "{$out}";
}
I gave it a lot of tests and couldn't break it!
It would be very interesting now to re-implement json_decode!
Thanks.
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;
I have 2 things I am trying to do here but I am miserably failing and I have tried everything so I don't know the reason.
I am trying to use str_replace to remove the copyright, but the copyright signature of the email is appearing.
For some reason, at random spots in the message, it's entering numbers. I am really confused why this is happening. Below is the PHP code and how the HTML output looks.
**** NEW Output:****
I added the qprint and now I get:
Output:
Code:
<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'username#gmail.com';
$password = 'Password';
/* try to connect */
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox, 'ALL');
/* if emails are returned, cycle through each... */
if ($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach ($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox, $email_number, 0);
$message = imap_fetchbody($inbox, $email_number, 2);
$DateFormatted = str_replace("-0500", "", $overview[0] -> date);
/* output the email header information */
$output .= '<span class="msg_subject">' . $overview[0] -> subject . '</span> | ';
$output .= '<span class="msg_date"> ' . $DateFormatted . '</span><br />';
$bodyFormatted = str_replace("This e-mail (and attachment(s)) is confidential, proprietary, may be subject to copyright and legal privilege and no related rights are waived. If you are not the intended recipient or its agent, any review, dissemination, distribution or copying of this e-mail or any of its content is strictly prohibited and may be unlawful. All messages may be monitored as permitted by applicable law and regulations and our policies to protect our business. E-mails are not secure and you are deemed to have accepted any risk if you communicate with us by e-mail. If received in error, please notify us immediately and delete the e-mail (and any attachments) from any computer or any storage medium without printing a copy.
Ce courriel (ainsi que ses pièces jointes) est confidentiel, exclusif, et peut faire l’objet de droit d’auteur et de privilège juridique; aucun droit connexe n’est exclu. Si vous n’êtes pas le destinataire visé ou son représentant, toute étude, diffusion, transmission ou copie de ce courriel en tout ou en partie, est strictement interdite et peut être illégale. Tous les messages peuvent être surveillés, selon les lois et règlements applicables et les politiques de protection de notre entreprise. Les courriels ne sont pas sécurisés et vous êtes réputés avoir accepté tous les risques qui y sont liés si vous choisissez de communiquer avec nous par ce moyen. Si vous avez reçu ce message par erreur, veuillez nous en aviser immédiatement et supprimer ce courriel (ainsi que toutes ses pièces jointes) de tout ordinateur ou support de données sans en imprimer une copie.", "", $message);
/* output the email body */
$output .= '<span class="msg_body">' . $bodyFormatted . '</span><br /><br />';
}
echo $output;
}
/* close the connection */
imap_close($inbox);
?>
I don't know which format the email is coming across as, but it looks like you need to use imap_qprint($message); to get the message in the correct format, then do str_replace('©','',$bodyFormatted); because it should be in HTML.
The random numbers are from not using imap_qprint(). You have 8bit strings inside your message that need to be converted.
Here's the modified code:
/* get information specific to this email */
$overview = imap_fetch_overview($inbox, $email_number, 0);
$message = imap_fetchbody($inbox, $email_number, 2);
$message = imap_qprint($message);
$DateFormatted = str_replace("-0500", "", $overview[0] -> date);
/* output the email header information */
$output .= '<span class="msg_subject">' . $overview[0] -> subject . '</span> | ';
$output .= '<span class="msg_date"> ' . $DateFormatted . '</span><br />';
$string = "you should get the HTML and put it in there, I'm sure there are things like and other html chars that it's not finding";
$bodyFormatted = str_replace($string, "", $message);
/* output the email body */
$output .= '<span class="msg_body">' . $bodyFormatted . '</span><br /><br />';