Could someone help me with this?
I have a folder with some files (without extention)
/module/mail/templates
With these files:
test
test2
I want to first loop and read the file names (test and test2) and print them to my html form as dropdown items. This works (the rest of the form html tags are above and under the code below, and omitted here).
But I also want to read each files content and assign the content to a var $content and place it in an array I can use later.
This is how I try to achieve this, without luck:
foreach (glob("module/mail/templates/*") as $templateName)
{
$i++;
$content = file_get_contents($templateName, r); // This is not working
echo "<p>" . $content . "</p>"; // this is not working
$tpl = str_replace('module/mail/templates/', '', $templatName);
$tplarray = array($tpl => $content); // not working
echo "<option id=\"".$i."\">". $tpl . "</option>";
print_r($tplarray);//not working
}
This code worked for me:
<?php
$tplarray = array();
$i = 0;
echo '<select>';
foreach(glob('module/mail/templates/*') as $templateName) {
$content = file_get_contents($templateName);
if ($content !== false) {
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"$i\">$tpl</option>" . PHP_EOL;
} else {
trigger_error("Cannot read $templateName");
}
$i++;
}
echo '</select>';
print_r($tplarray);
?>
Initialize the array outside of the loop. Then assign it values inside the loop. Don't try to print the array until you are outside of the loop.
The r in the call to file_get_contents is wrong. Take it out. The second argument to file_get_contents is optional and should be a boolean if it is used.
Check that file_get_contents() doesn't return FALSE which is what it returns if there is an error trying to read the file.
You have a typo where you are referring to $templatName rather than $templateName.
$tplarray = array();
foreach (glob("module/mail/templates/*") as $templateName) {
$i++;
$content = file_get_contents($templateName);
if ($content !== FALSE) {
echo "<p>" . $content . "</p>";
} else {
trigger_error("file_get_contents() failed for file $templateName");
}
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"".$i."\">". $tpl . "</option>";
}
print_r($tplarray);
Related
I've created a page that grabs data from a CSV (http://liamjken.com/aim-parse/aim-websites-new.csv) and displays it on this page http://www.liamjken.com/aim-parse/parse.php?17
?17 references the row in the csv file. so if I change that to ?10 it pulls the info from a different row.
What I would like to do instead of using the row number is use the $vin_num value. so if I put ?1FMCU9GD9KUC40413 at the end of the URL it would display the row that contains that Number.
here is the code I have currently, its basically cobbled together from multiple different trends I found so if you notice other potential problems id be happy to hear about them.
<?php
$qstring = $_SERVER['QUERY_STRING'];
$row = $qstring; // The row that will be returned.
$data = get_row('aim-websites-new.csv', $row);
'<pre>'.print_r($data).'</pre>';
function get_row($csv, $row) {
$handle = fopen("$csv", 'r');
$counter = 0;
$result = '';
while ( ($data = fgetcsv($handle)) !== FALSE ) {
$counter++;
if ( $row == $counter ) {
$vin_num="$data[12]";
$model="$data[10]";
$make="$data[9]";
$year="$data[8]";
ob_start();
?>
<h1>VIN: <?php echo $vin_num; ?></h1>
<h1>Year: <?php echo $year; ?></h1>
<h1>Make: <?php echo $make; ?></h1>
<h1>Model: <?php echo $model; ?></h1>
<?php
$output = ob_get_clean();
ob_flush();
return $output;
}
}
}
?>
<?php
function extract_data($file)
{
$raw = file($file); // file() puts each line of file as string in array
$keys = str_getcsv(array_shift($raw)); // extract the first line and convert into an array
// Look through the rest of the lines and combine them with the header
$data = [];
foreach ($raw as $line) {
$row = str_getcsv($line);
$data[] = array_combine($keys, $row);
}
return $data;
}
function get_record($data, $vin)
{
foreach ($data as $record) {
if ($record['VIN'] === $vin)
return $record;
}
return null;
}
$data = extract_data('aim-websites-new.csv');
$vin = $_SERVER['QUERY_STRING'];
if (empty($vin)) {
echo '<h1>No VIN provided</h1>';
exit;
}
$record = get_record($data, $vin);
if ($record === null) {
echo '<h1>No record found</h1>';
exit;
}
echo '<h1>' . $record['VIN'] . '</h1>';
echo '<h1>' . $record['Year'] . '</h1>';
echo '<h1>' . $record['Make'] . '</h1>';
echo '<h1>' . $record['Model'] . '</h1>';
echo '<pre>' . print_r($record, true) . '</pre>';
If you don't trust that the records will have valid VINs, you can use the code posted here to validate: How to validate a VIN number?
currently internship I have to make a website with the establishment of an external API, I can display the data, parcontre I would like the displays in a <select>
However when I make my code nothing is displayed, however if I display it in a data p appears but in a table, how to display the data in a <select>
function dog_func ($atts) {
$contents = file_get_contents('https://dog.ceo/api/breeds/list/all');
$contents_arr = json_decode($contents);
echo "<select>" . $contents ."</select>" ;
}
add_shortcode ('dog_api', 'dog_func');
OR
function dog_func ($atts) {
$contents = file_get_contents('https://dog.ceo/api/breeds/list/all');
$contents_arr = json_decode($contents);
echo '<select multiple value="$contents"></select>';
}
add_shortcode ('dog_api', 'dog_func');
During these tests nothing is displayed
AND
function dog_func ($atts) {
$contents = file_get_contents('https://dog.ceo/api/breeds/list/all');
$contents_arr = json_decode($contents);
echo "<p>" . $contents ."</p>" ;
}
add_shortcode ('dog_api', 'dog_func');
Walk but display in "gross"
You can do this for <select> like this
$contents_arr = json_decode($contents);
echo '<select>';
foreach($contents_arr->message as $key=> $ca){
echo "<option value='".$key."'>" . $key ."</option>" ;
}
echo '</select>';
And for <p>
$contents_arr = json_decode($contents);
foreach($contents_arr->message as $key=> $ca){
echo "<p>" . $key ."</p>" ;
}
It's actually a json object which you can decode it into the array and then parse it through foreach loop
First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);
I have a piece of code like this:
$classVoHeader = 'class C'.toCamelCase($tableName,true).'Vo{';
$classVoFooter = '}';
$str ='public $table_map = array(';
$propertyStr = '';
foreach($columnInfos as $column){
$str.=$br.'\''.$column['Field'].'\' => \''.toCamelCase($column['Field']).'\',';
$propertyStr.=$br.'public $'.toCamelCase($column['Field']).';';
}
$str.=$br.');';
echo $classVoHeader.$br;
echo $str;
echo $propertyStr.$br;
echo $classVoFooter;
And I want to create a php file that have content is all of what it echoed.
Is it impossible?
Take a look at http://www.php.net/manual/en/function.ob-get-contents.php to save what is being printed into a buffer, then use http://www.php.net/manual/en/function.file-put-contents.php to save this string to a file
Strange question but, here you go:
$Result = '<?php ' . $classVoHeader.$br . $str . $propertyStr.$br . $classVoFooter . ' ?>';
$file = fopen("result.php","w");
echo fwrite($file,$Result);
fclose($file);
i dont know what your code is and it doesnt matter. With my answer you will have all the output that is produced between ob_start(); and ob_get_clean(); saved to the variable $the_output_of_code. Then just write this to a file.
<?php
ob_start();
// your code begins here
// [your piece of code here whatever]
$classVoHeader = 'class C'.toCamelCase($tableName,true).'Vo{';
$classVoFooter = '}';
$str ='public $table_map = array(';
$propertyStr = '';
foreach($columnInfos as $column){
$str.=$br.'\''.$column['Field'].'\' => \''.toCamelCase($column['Field']).'\',';
$propertyStr.=$br.'public $'.toCamelCase($column['Field']).';';
}
$str.=$br.');';
echo $classVoHeader.$br;
echo $str;
echo $propertyStr.$br;
echo $classVoFooter;
// your code ends here
$the_output_of_code = ob_get_clean();
$file = fopen("the_output.php","w");
fwrite($file,$the_output_of_code);
fclose($file);
?>
So I am using Codeignitor and I am trying to figure out the best way to share my constants with my javascript in a neat maintainable way.
1) in the view I could echo out my variables in like my footer (yuuuck!)
2) I could parse a partial view which contains a template for javascript and inject that in my view (maybe?)
3) I could dynamically create a javascript file like myJavascript.js.php and include that in my header.
What's the best maintainable way to implement PHP into JS in a MVC framework?
To keep my variables nicely wrapped I use a JSON object - that way I won't incur in issues with encoding, slashes, having to manually update the JavaScript every variable I add...
$variables_to_view['js_variables']['var_name'] = $var_name;
then pass it to the view
php_variables = <?php echo json_encode($js_variables) ?>;
alert(php_variables.var_name);
There doesn't seem to be anything wrong about echoing your variables in the script tag. In fact, frameworks like BackboneJS are encouraging you to do so for data you need to pass to your client-side code.
You can use short tag like this:
For Example:
You want to use $abc variable in js, then you will need to write this in js
var abc = <?=$abc?>;
You can create php file .
Something like script.js.php?outfor=1;
<?php
header("Content-type:text/javascript"); //can be application/javascript.
?>
ABC = <?php echo $abc?>
CBA = <?php echo $cba?>
BAC = <?php echo $bac?> //and so on.
Some additional info .
If you use "var" in function that variable will be visible only in that function and without "var"means global.
So.
function abc()
{
var a = 1; //only in abc()
b=2; //global
}
I know that in terms of programming skills it's not the best, but finally it's what I use and it's working. To make it short: I put all my constants in a xml file and I have this little script that generates two separate files with the same content, but different syntax. I am just pasting the code with my values. If it's useful for anybody, I'll be very happy to help.
The xml is the simplest possible; value
<?php
define("GECOXML_PATH","../xml/geco.xml");
define("PHP_GECO_FN","../.includes/geco.php");
define("JS_GECO_FN","../js/geco.js");
echo "******** GECO (GEnerate COnstants files for PHP and JS) **********<br>";
echo "<br>";
echo " input xml file: ". GECOXML_PATH."<br>";
echo " output php file: ". PHP_GECO_FN."<br>";
echo " output js file: ". JS_GECO_FN."<br>";
echo "********************************************************************<br>";
$geco = (object)xmlParse(GECOXML_PATH);
echo "<br>";
echo "<br>";
echo "************ PHP GECO ************* <br>";
echo "<br>";
$PHP = gecoPHP($geco);
echo "<br>";
echo "<br>";
echo "************** JS GECO ************<br>";
echo "<br>";
$JS = gecoJS($geco);
writeFiles($PHP, $JS);
//****** Functions *********
function xmlParse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
return simplexml_load_string($fileContents);
}
function writeFiles($PHPcontent, $JScontent)
{
echo "<br> PhP ok:". file_put_contents(PHP_GECO_FN, $PHPcontent) . "<br>";
echo "<br> JS ok:" . file_put_contents(JS_GECO_FN, $JScontent) . "<br>";
}
function gecoPHP($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "define(\"" . $key . "\",". intval($value) . ");\n";
}
else
{
$line = "define(\"" . $key . "\",\"". $value . "\");\n";
}
$phpContent = $phpContent . $line;
echo $line."<br>";
}
return "<?php\n"$phpContent."?>";
}
function gecoJS($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "var " . $key . "=". $value . ";\n";
}
else
{
$line = "var " . $key . "=\"". $value . "\";\n";
}
$JSContent = $JSContent . $line;
echo $line."<br>";
}
return $JSContent;
}
?>