I'm calling a python script from my PHP code, I need to pass 7 variable: a few strings, a couple of array and a matrix.
I tried to use both Shell_Exec and exec(), but I get always the same problem:
matrixdata = sys.argv[7]
IndexError: list index out of range
The first thought was " I passed the wrong number of variable ", but checking they are 7.
This is my python code:
listlabel = str(sys.argv[2])
listdata = (sys.argv[1])
typechart = str(sys.argv[3])
name = str(sys.argv[4])
typedata = str(sys.argv[5])
title = str(sys.argv[6])
matrixdata = sys.argv[7] //this is the matrix
This is my PHP Lines to call it
//json encoding for the array:
$total = json_encode(compact($listlabel));
$event = json_encode(compact($listdata));
$event = json_encode(compact($matrixdata));
exec("python ../home/path../create_chart.py $total $event $chart $name $typedata $title $matrixdata", $output);
//all the parameters exist and the path is correct
I'm passing 7 arguments, I'm getting 7 arguments. I don't understand where the problem is.
Before to added the last matrix, this line was working with 7 elements, instead of 7, I also tried with 8 elements and 9 instead of 7, but no luck.
Let me know if someone can help me, thank you.
Related
I am trying to implement a logging library which would fetch the current debug level from the environment the application runs in:
23 $level = $_SERVER['DEBUG_LEVEL'];
24 $handler = new StreamHandler('/var/log/php/php.log', Logger::${$level});
When I do this, the code fails with the error:
A valid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores at line 24.
How would I use a specific Logger:: level in this way?
UPDATE:
I have tried having $level = "INFO" and changing ${$level} to $$level. None of these changes helped.
However, replacing the line 24 with $handler = new StreamHandler('/var/log/php/php.log', Logger::INFO); and the code compiles and runs as expected.
The variable itself is declared here
PHP Version => 5.6.99-hhvm
So the answer was to use a function for a constant lookup:
$handler = new StreamHandler('/var/log/php/php.log', constant("Monolog\Logger::" . $level));
<?php
class Logger {
const MY = 1;
}
$lookingfor = 'MY';
// approach 1
$value1 = (new ReflectionClass('Logger'))->getConstants()[$lookingfor];
// approach 2
$value2 = constant("Logger::" . $lookingfor);
echo "$value1|$value2";
?>
Result: "1|1"
Okay I am using a framework so I can pull database rows like: $username->thenthenameoftherow
But the row I want it to bet a variable because the variable is defined via a post method, I run that variable through an explode to get the first part, the text before the _
Yet when I run: and get currency like:
$coin = $_POST['coin'];
//currency they want to user
$currency = explode('_', $coin);
$username->$currency[1]
I can't set a hardcoded row for that, it has to be a userdefined viariable
I get the error:
Notice: Undefined property: stdClass::$usd in C:\xampp\htdocs\mvc\application\controllers\dashboard.php on line 193
Using mini mvc framework
Okay, for an exampple the post to set the $coin is BTC_USD I then explode it to remove the _ and get the 2nd part of the string which is USD I then want to get the USD table from my database by running the user query but I get that error.
Your code is basically:
$_tmp = $username->$currency;
$result = $_tmp[1];
Did you mean:
$_tmp = $currency[1];
$result = $username->$_tmp;
? Because if so, you want:
$result = $username->{$currency[1]};
do you mean
$username->currency[1]
without $ before currency
Up until yesterday I had a perfectly working budget organizer site/app working with iGoogle.
Through PHP, using the following little line
file_get_contents('http://www.google.com/ig/calculator?hl=en&q=1usd=?eur');
and similar I was able to get all I needed.
As of today, this is no longer working. When I looked into the issue, what has happened is that Google has retired iGoogle. Bummer!
Anyway, I was looking around elsewhere but I can't find anything that fits my needs. I would REALLY love to just fix it and get it running again by just switching this one line of code (i.e. changing the Google address with the address of some other currency API available) but it seems like none does.
The API from rate-exchange.appspot.com seems like it could be a iGoogle analog but, alas, it never works. I keep getting an "Over Quota" message.
(Here comes an initial question: anybody out there know of a simple, reliable, iGoogle-sort API?)
So I guess the natural thing would be to the Yahoo YQL feature (at least I suppose it is as reliable).
Yahoo's queries look like this:
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN")&env=store://datatables.org/alltableswithkeys
What I really can't figure out is how to parse this data. It outputs an XML.
What I used to have is this:
function exchange($inputAmount,$inputCurrency,$outputCurrency) {
$exchange = file_get_contents('http://www.google.com/ig/calculator?hl=en&q='.$inputAmount.$inputCurrency.'=?'.$outputCurrency);
$exchange = explode('"', $exchange);
$exchange = explode('.', $exchange['3']);
$exchange[0] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[0]));
if(isset($exchange[1])){
$exchange[1] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[1]));
$exchange = $exchange[0].".".$exchange[1];
} else{
$exchange = $exchange[0];
}
return $exchange;
}
So the user was able to get the exchange rate from an input currency such as "USD" and an output currency such as "EUR" on a specific amount of money. As I said, this was working swimmingly up until yesterday night.
Any ideas?
Never mind! Solved it!
For anyone interested, here's what I did to get my code to work (with the least chnges possible) with the Yahoo YQL:
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "EURUSD")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
'usd' => $exchange['USD to EUR'], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
'eur' => 1); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
$tousd = array(
'eur' => $exchange['EUR to USD'],
'usd' => 1);
This is basically all you need to get all the exchange info you want. After that, you use it all something like this:
amount*$toxxx['coin'];
So, say I wanted to know how many Euro is 100 USD right now:
100*$toeur['usd'];
Piece of cake!
Still a very useful solution by QuestionerNo27. Since early 2015, however, Yahoo YQL apparently slightly changed the XML output of their api. 'Name' now no longer translates into a string like 'USD to EUR', but to 'USD/EUR' and should in the code above be referenced this way:
$toeur = array(
'usd' => $exchange['USD/EUR']
instead of
$toeur = array(
'usd' => $exchange['USD to EUR']
and in a similar fashion for other currency conversions.
I created a routine to convert the currency based on #QuestionerNo27 http://jamhubsoftware.com/geoip/currencyconvertor.php?fromcur=USD&tocur=EUR&amount=1 you can consume this
<?php
$fromcur = $_GET['fromcur'];
$tocur = $_GET['tocur'];
$amt = $_GET['amount'];
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("'.$fromcur.$tocur.'")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$conv = $fromcur . '/' . $tocur;
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
$tocur => $amt*$exchange[$conv], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
$fromcur => $amt,
"ex_amt" =>$amt*$exchange[$conv]); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
echo json_encode($toeur);
?>
This question already has answers here:
Multiple returns from a function
(32 answers)
Closed 6 years ago.
I'm building a script to work with PxPost from Payment Express and I've used their sample code as can be found at http://www.paymentexpress.com/Technical_Resources/Sample_code_-_PHP/PX_Post_-_cURL.aspx
How it works: It's built into an automated script that queries orders from my database, processes them, and returns a value.
My only problem is I want the function to return more than one value, so this is what I've done.
Code to run through functions (Line 201):
$once_complete = process_request($billingID, $order_total, $merchRef);
Which send the payment to be processed, that then gets the returns and processes the XML using the sample code. At the end of the code I've removed all the $html info and just replaced it with the following (line 111):
return $CardHolderResponseDescription.":".$MerchantResponseText.":".$AuthCode.":".$MerchantError;
Which should as far as I understand, return that to what started it. I then want to split those values and return them as strings using the following (line 202):
list($RespDesc, $MerchResp, $AuthCode, $MerchError) = explode(":", $once_complete);
But for some reason that's not working.
I've tried echo-ing the return and it works fine then, but then after that it seems to disappear. What may be going wrong?
You can see the entire page's code at http://pastebin.com/LJjFutne. This code is a work in progress.
Return an array.
function process_request(){
...
return array( $CardHolderResponseDescription, $MerchantResponseText, $AuthCode, $MerchantError );
}
And pick it up via:
$_result = process_request();
$CardHolderResponseDescription = $_result[0];
$MerchantResponseText = $_result[1];
...
Tip: use shorter vars for better reading :)
In your function process_request:
return array($CardHolderResponseDescription, $MerchantResponseText, $AuthCode, $MerchantError);
When calling your function:
list($RespDesc, $MerchResp, $AuthCode, $MerchError) = process_request($billingID,$order_total,$merchRef);
The simplest thing you can do is putting the return values in an array which you can access later:
return array("CardHolderResponseDescription"=>$CardHolderResponseDescription, "MerchantResponseText" => $MerchantResponseText, "AuthCode" => $AuthCode );
And later:
list($RespDesc, $MerchResp, $AuthCode, $MerchError) = $my_return_value
I am having a problem passing an array variable from Flash (AS2) to PHP. In action script I have several arrays defined like this
output["px1"]
output["px2"]
output["px3"]
and then I use the following code to pass the variables into a php file
output.sendAndLoad("orders/print2cart.php",output,"POST");
I want to know how to get the data from the array in PHP. I have tried using $_POST['px1'], $_POST['output']['px1'], $_POST['output'] but I cannot seem to get any data. Any ideas as to what I can change to get the desired result?
Thanks!
EDIT: Just noticed that I one of the other variables in output (output.username) is also not being sent to PHP, despite it showing up in flash. Using the following code to alert to flash and it does show all the variables correctly.
getURL("javascript:alert('Print Stamp: " + output.PrintStamp + " User: " + output.username "')");
EDIT: Seems like once I send a pretty long array (or a string for that matter) none of the other fields associated with the LoadVars variable are sent either. I googled it up for limits and it says text limits are ~ 63000. Still not sure if that is the problem
Try it as a String.
Use Array.join(); in flash and send the value returned by that, then use explode() in PHP convert it back to an array.
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
dataOut.info = your_array.join("#");
vars.sendAndLoad("url", dataIn, "post");
dataIn.onLoad = function(go:Boolean):Void
{
if(go)
{
trace('success');
}
else trace('connection failed');
}
The PHP:
<?php
$str = $_POST["info"];
$myarray = explode($str);
?>
Since there were no other alternatives and I went through a lot of stuff before finally concluding that Arrays of large sizes cannot be passed through from AS2 to PHP very easily. My array was actually an image converted to pixels, so what I did was that I split the array into 2 pieces and posted to the PHP file twice instead of only once. Another alternative would be to split and post the array to a text file first and then read that text file directly from PHP.
You can do the same as you would do with HTML, by naming your parameters "array[0]", "array[1]", etc... :
var urlVariable:URLVariables = new URLVariables();
urlVariable["phpArray[0]"] = "arrayEntry0";
urlVariable["phpArray[1]"] = "arrayEntry1";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://yourserver.com/phpScript.php");
request.method = URLRequestMethod.POST;
request.data = urlVariable;
loader.load(request);
then serverside you can verify the result received by php script :
print_r($_POST);
it should output :
Array
(
[phpArray] => Array
(
[0] => arrayEntry0
[1] => arrayEntry1
)
)
and for multiple dimension array you can use :
urlVariable["phpArray[0][0]"]