I have searched the internet, but the results I have seen are not clear enough.
I was able to add a manifest.json file into my wordpress theme by adding this code to the functions.php file.
//manifest file
add_action( 'wp_head', 'inc_manifest_link' );
// Creates the link tag
function inc_manifest_link() {
echo '<link rel="manifest" href="'.get_template_directory_uri().'/manifest.json">';
}
The manifest.json is as it should be.
However I wish to use some theme_mod functions within the manifest file. Which I can't do without php.
So is there anyway to write php code within the manifest.json file.
Thanks in advance.
So you can do something like this:
<?php
$filename = "manifest.json";
// Grab contents and decode them into an array
$data = json_decode(file_get_contents($filename), true);
//this is where you're adding your content so below you can write to the file
//Creating new var
//(make sure no var has the name "['newnewname']" unless you want to edit it)
$data['newname'] = 'Adding NEW contents';
//Creating new 2 dimensional array
$data['newname'] = array("another1" => "val1", "another2" => "val2");
//adding content to an existing 2 dimensional array
$data['exists'] += array("another1" => "val1", "another2" => "val2");
//adding content to an existing 3 dimensional array
$data['exists']['name'] += array("another1" => "val1", "another2" => "val2");
//adding content to an existing 4 dimensional array
$data['exists']['name']['name'] += array("another1" => "val1", "another2" => "val2");
// encode back into json
$jencode = json_encode($data);
// write over file with new contents
$fopen = fopen($filename, "w");
if(fwrite($fopen, $jencode)){
echo('Success!<hr>');
echo(file_get_contents($filename));
}
fclose($fopen);
Heres a live example (with fopen/write/read stuff removed):
Advanced: http://sandbox.onlinephpfunctions.com/code/eacdd6b8254c2127521769461d5f6d9daeda224d
Simple: http://sandbox.onlinephpfunctions.com/code/3589151881aac2e442738b381c05a37240081901
Related
I want to convert the array data into HTML format and want to save the file as a .html file. How can I do this?
Suppose the array is:
Array
(
[0-50] => 880
[50-100] => 5
[100-150] => 1
[550-600] => 1
)
And I am writting a file like this:
<?php
$file = fopen("abc.html","w");
?>
I can write this file as a CSV format easily but how can I do this to store a html file from data?
my expected result is -
Distance trips
0-50 880
50-100 5
100-150 1
550-600 1
distance and trips here are the table header and in distance field all are the keys of the array and in trips all are the values of the array.
Suppose i have written the data into this file ->
$html['head'] = '<html><head></head><body>';
$html['content'] = "<table><tr style='background-color:cyan'><td>Distance</td><td>total Trips</td></tr>";
foreach($de as $key=>$value)
{
$html['content'] .="<tr style='background-color:yellow'><td>$key</td><td>$value</td></tr>";
}
$html['foot'] = '</table></body>';
file_put_contents("abc.html", $html);
Now i wanted to append this file with this data ->
$html['head'] = '<html><head></head><body>';
$html['content'] = "<h2>Data Regarding 0 - 50 km distance</h2>
<table width=900 border=5>
<tr style='background-color:cyan font-size:24px'>
<td>S.No</td>
<td>Customer Id</td>
<td>Total Distance</td>
<td>Total Trips</td>
<td>Average Speed</td>
";
foreach($dec as $result=>$value) {
$html['content'] .= "<tr style='background-color:lightgreen'><td>$value[cid]</td><td>$value[totalDistance]</td><td>$value[totalTrips]</td><td>$value[avgSpeed]</td></tr>";
}
$html['foot'] = '</table></body></html>';
Since you place dynamic information in static HTML document, you need to rewrite this information on each edit.
Use some PHP library to read HTML file (like HTML DOM Parser)
Gather all table information from HTML file.
Append new information (or insert where needed).
Write new content to HTML file.
I suggest to save this information to some structured format (like json file or database) and when showing information, just read this data. It would be much easier to implement.
E.g. rewriting data in json file:
$json = json_decode(file_get_contents('data.json'), true);
$json = array_merge($json, $newData);
file_put_contents(json_encode($json));
For the first table you want to put in a html file, this will do the work using your methodology :
<?php
//Creating the array
$de = Array("0-50" => 880,
"50-100" => 5,
"100-150" => 1,
"550-600" => 1
);
//creating the array corresponding to html code
$html = array();
//Creating the header
$html['head'] = '<html><head></head><body>';
//creating content - table header
$html['content'] = "<table><tr style='background-color:cyan'><td>Distance</td><td>total Trips</td></tr>";
foreach($de as $key=>$value)
{
$html['content'] .="<tr style='background-color:yellow'><td>$key</td><td>$value</td></tr>";
}
//footer
$html['foot'] = '</table></body>';
//no need to use fopen because file_put_contents manages that.
file_put_contents("abc.html", $html);
?>
But for the second part of your question, the same logic will work, just be careful how you use array, specially here :
foreach($dec as $result=>$value)
{
$html['content'] .= "<tr style='background-color:lightgreen'><td>$value[cid]</td><td>$value[totalDistance]</td><td>$value[totalTrips]</td><td>$value[avgSpeed]</td></tr>";
}
You should write it this way :
foreach($dec as $result=>$value)
{
$html['content'] .= "<tr style='background-color:lightgreen'><td>".$value['cid']."</td><td>".$value['totalDistance']."</td><td>".$value['totalTrips']."</td><td>".$value['avgSpeed']."</td></tr>";
}
Hi hope it helped.
What you are looking for is the Append Mode.
a => Open for writing only;
Or
a+ => Open for reading and writing;
What this mode does is "place the file pointer at the end of the file. If the file does not exist, attempt to create it."
So your fopen line becomes ...
$file = fopen("abc.html","a");
This ways you can always append whatever you want.
I am using the following code to initiate a python script and pass a php variable to it.
$tmp = exec("python path/to/pythonfile.py $myVariable $mySecondVariable", $output);
This works very well, my issue is that I will need to pass 100+ variables to the python script. I don't want this exec line to become extremely long and unmanageable. I have also explored passing a php array instead of a variable with the following code:
$checked = array(
"key1" => "1"
"key2" => "1"
"key3" => "1"
);
$checkedJson = json_encode($checked);
$tmp = exec("python path/to/pythonfile.py $myVariable $checkedJson", $output);
With this I have been unable to decode the JSON on the python side. I have been able to do a basic print of the array variable(undecoded) in python, but it gives every individual character as a new array value. ie [0] = k, [1] = e, [2] = y, [3] = 1, etc...
Any help is greatly appreciated.
Just to be clear,I am looking for a simpler method than encoding and decoding an array. Is there a way I can format the exec line to allow for multiple variables.
Store your PHP variables within a temporary text file then use python to read that file.
Simple and effective.
Assuming Scripts are in the same directory
PHP Portion
long version (self contained script - skip to the short version below if you only want the code snippet)
<?php
#Establish an array with all parameters you'd like to pass.
#Either fill it manually or with a loop, ie:
#Loop below creates 100 dummy variables with this pattern.
#You'd need to come up with a way yourself to fill a single array to pass
#$variable1 = '1';
#$variable2 = '2';
#$variable3 = '3';
#....
#$variableN = 'N';
#...
for ($i=1; $i<=100; $i++) {
${'variable'.$i} = $i;
}
#Create/Open a file and prepare it for writing
$tempFile = "temp.dat";
$fh = fopen($tempFile, 'w') or die("can't open file");
#let's say N=100
for ($i=1; $i<=100; $i++) {
#for custom keys
$keyname = 'Key'.$i;
# using a variable variable here to grab $variable1 ... $variable2 ... $variableN ... $variable100
$phpVariablesToPass[$keyname] = ${'variable'.$i} + 1000;
}
#phpVariablesToPass looks like this:
# [Key1] => 1001 [Key2] => 1002 [Key3] => 1003 [KeyN] = > (1000+N)
#now write to the file for each value.
#You could modify the fwrite string to whatever you'd like
foreach ($phpVariablesToPass as $key=>$value) {
fwrite($fh, $value."\n");
}
#close the file
fclose($fh);
?>
or in short, assuming $phpVariablesToPass is an array filled with your values:
#Create/Open a file and prepare it for writing
$tempFile = "temp.dat";
$fh = fopen($tempFile, 'w') or die("can't open file");
foreach ($phpVariablesToPass as $key=>$value) {
fwrite($fh, $value."\n");
}
fclose($fh);
Python Snippet to Grab the Data
lines = [line.strip() for line in open('temp.dat')]
the variable lines now contains all of your php data as a python list.
I have a custom content type in Drupal that allows multiple image uploads through a single field. I want to programmatically access the image URI's, apply my theme, and then get the output one by one. I can do this with a single image like so,
<?php
$image_style_name = 'my_theme';
$image_uri = $entity->field_image['und'][0]['uri'];
$image = theme('image_style', array('style_name' => $image_style_name, 'path' => $image_uri));
$image = image_style_url($image_style_name, $image_uri); ?>
but I am unsure how to access the entire array of images.
For anyone who needs it... the full solution:
<?php
$image_style_name = 'my_theme';
foreach($entity->field_image['und'] as $key => $value){
$image_uri = $entity->field_image['und'][$key]['uri'];
$image = theme('image_style', array('style_name' => $image_style_name, 'path' => $image_uri));
$output = image_style_url($image_style_name, $image_uri);
echo $output;
}
?>
They should be in the $entity->field_image['und'] array so you should be able to loop over the array and theme each one with something like
foreach($entity->field_image['und'] as $image_field){
..etc
}
Im using PHP to create a playlist. Two random songs are chosen from a directory, and their name and location are stored in an array and then written to a file via json_encode().
$arraySongs[] = array('name' => $songName , 'mp3' => $webUrl);
This works great. I can make a very long playlist, two songs at a time. Id also like to remove songs, so I have an AJAX powered delete button, that posts the id of the track to be deleted, PHP then loads the whole tracklist...
$decoded = json_decode(file_get_contents($tracklist),true);
and removes the given song from the array, then re encodes and re writes the json text file. This all works great.
The problem comes whenever I try to delete anything with a playlist of more than 10 items.
Typically, my song.json file goes [{name:song1,mp3:song url},{name:song2,mp3:song2 url}]
However, when I have a list of more than 10 items, the re encoded playlist looks like this:
[{ ... },{name:song9,mp3:song9 url}],[10,{"name":song10,mp3:song10 url}]
Why is my re-encoded array get that strange [10,{"name"... [11,{"name"... [12,{"name"...
but everything below 10 is always fine?
Thanks for reading this! Any suggestions would be greatly appreciated, this is driving me nuts!
Here is the code im Using:
<?php
$json = "song.php";
$decoded = json_decode(file_get_contents($json),true);
$playlist = array();
$names = array();
// Now Get i From Javascript
$i=$_POST['id'];
//Select i's Array
$collect_array=$decoded[$i];
while (list ($key, $val) = each ($collect_array)) {
//Remove i's Values
//echo "<br />$key -> $val <br>";
unset($decoded[$i]);
}
//Take all the remaining arrays
$collect_array=$decoded;
while (list ($key, $val) = each ($collect_array)) {
$arraySongs[] = array($key , $val);
}
// Our New Array ready for json.
$jsonData = json_encode($arraySongs);
// open song.php and scribble it down
$tracklist = $json;
$fh = fopen($tracklist, 'w') or die("can't open filename: $tracklist");
fwrite($fh, $jsonData);
fclose($fh);
?>
try removing elements with unset
debug your code (not posted in the thread, so do it yourself) by adding a line where you var_dump or print_r the whole thing before json_encode
or it's a bug in json_encode which would not be nice...
Encode the track ID on 2 or even 3 digits using the php function sprintf with parameter %02d.
This worked fine for me.
Am developing an admin center where I can edit configuration files (written in PHP). I do NOT want to store these values in a mySQL table (for various reasons). So say my config.php has contents like:
<?php
$option1 = 1;
$option2 = 2;
$option4 = 5;
$option7 = array('test','a','b',c');
?>
Now say in one of the admin pages I will only be changing a few values like option2 or option4 etc. Any ideas on what would be the best way to go about this.
I know one option is to read the PHP file completely and write parts of it using REGEX. Any way to make this more efficent? I don't want the config.php file to break because of some error on the user's end. Any ideas on how to ensure that it works?
If you have some liberty about the way you store configuration values, you may use ini files.
All you have to do is load the content of the ini file in an array with parse_ini_file, then modify values in that array and finally overwrite the file with new values, as described in this comment.
For obvious security reasons it's a good idea to place those files out of your document root.
sample content of ini file :
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
sample code (using safefilewrite function) :
<?php
$ini_file = '/path/to/file.ini';
$ini_array = parse_ini_file($ini_file);
$ini_array['animal'] = 'CAT';
safefilerewrite($file, implode("\r\n", $ini_array));
?>
var_export() is probably the function you're looking for.
You can write/read the settings to a file using the following code:
$content = array();
//fill your array with settings;
$fh = fopen ( $bashfile, 'w' ) or die ( "can't open file" );
fwrite ( $fh, $content );
fclose ( $fh );
to read it you use:
file_get_contents() //this will return a string value
OR
Line by line:
$lines = file('file.txt');
//loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
print "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}