i am trying to create some switches saved in other files, already tried to make it turn a text file into array but it didnt worked well since itdoesnt seem to even read the file properly and dont get anything from inside of it. now i got the idea of having php files that have the arrays and it can be changed by a main php file
this will be the entire switch file:
<?php
function getarray(){
$a = array(
'name_on' => 0,
'picture_on' = 0,
'custom_styling_on' = 0
);
return $a;
}
?>
and i would like to edit the values of the array from the main file, but i dont know exactly how.
but if someone know how to create an array from a text file it will work, but just remember i tried what the answer of other questions said to and didnt worked
as ADyson said
a json for an array will be way more useful, i have changed my code to,so if i press a button it will change the value:
<?php
function getvalues(){
$json = file_get_contents(__DIR__."\switch.json");
$arr = json_decode($json,true);
return $arr;
}
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['btn']))
{
setval('name',0);
}
function setval($key,$value){
$json = file_get_contents(__DIR__."\switch.json");
$arr = json_decode($json,true);
$arr[$key] = $value;
$jarr = json_encode($arr);
file_put_contents("switch.json",$jarr);
}
?>
Related
If you open the URL, you'll see that it's a very long string of sub objects. I want to extract the values for the 70 position. So far I've been able to extract the first tree without a problem ... But if you go deeper then I don’t get any feedback at all. Please check the code below and tell me, what am I doing wrong?
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port); // decode the JSON feed
echo $data[69]->port_name.'<br>';
echo $data[69]->port_status.'<br>';
echo $data[69]->passenger_vehicle_lanes->maximum_lanes.'<br>';
echo $data[69]->passenger_vehicle_lanes->standard_lanes->lanes_open.'<br>';
The following is working for me:
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port, true); // decode the JSON feed
echo "There are ".count($data)."Ports".PHP_EOL;
$found=false;
foreach ($data as $key => $value) {
//EDIT AFTER COMMENT**
if($value['port_number']==250401){
echo $value['port_name'].' '.$value['crossing_name'].PHP_EOL;
$found=true;
break;
}
}
if(!$found) echo "couldn't find port #";
can you try to change json_decode($port, true); (true will change object to array and it will be better to access it) like this and access it like in array echo $data[69]['passenger_vehicle_lanes']['maximum_lanes'].'<br>';
I wanna replace braces with <?php ?> in a file with php extension.
I have a class as a library and in this class I have three function like these:
function replace_left_delimeter($buffer)
{
return($this->replace_right_delimeter(str_replace("{", "<?php echo $", $buffer)));
}
function replace_right_delimeter($buffer)
{
return(str_replace("}", "; ?> ", $buffer));
}
function parser($view,$data)
{
ob_start(array($this,"replace_left_delimeter"));
include APP_DIR.DS.'view'.DS.$view.'.php';
ob_end_flush();
}
and I have a view file with php extension like this:
{tmp} tmpstr
in output I save just tmpstr and in source code in browser I get
<?php echo $tmp; ?>
tmpstr
In include file <? shown as <!--? and be comment. Why?
What you're trying to do here won't work. The replacements carried out by the output buffering callback occur after PHP code has already been parsed and executed. Introducing new PHP code tags at this stage won't cause them to be executed.
You will need to instead preprocess the PHP source file before evaluating it, e.g.
$tp = file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$tp = str_replace("{", "<?php echo \$", $tp);
$tp = str_replace("}", "; ?>", $tp);
eval($tp);
However, I'd strongly recommend using an existing template engine; this approach will be inefficient and limited. You might want to give Twig a shot, for instance.
do this:
function parser($view,$data)
{
$data=array("data"=>$data);
$template=file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$replace = array();
foreach ($data as $key => $value) {
#if $data is array...
$replace = array_merge(
$replace,array("{".$key."}"=>$value)
);
}
$template=strtr($template,$replace);
echo $template;
}
and ignore other two functions.
How does this work:
process.php:
<?php
$contents = file_get_contents('php://stdin');
$contents = preg_replace('/\{([a-zA-Z_][a-zA-Z_0-9]*)\}/', '<?php echo $\1; ?>', $contents);
echo $contents;
bash script:
process.php < my_file.php
Note that the above works by doing a one-off search and replace. You can easily modify the script if you want to do this on the fly.
Note also, that modifying PHP code from within PHP code is a bad idea. Self-modifying code can lead to hard-to-find bugs, and is often associated with malicious software. If you explain what you are trying to achieve - your purpose - you might get a better response.
I am attempting to get a JSON feed output from attributes of an XML feed. I can get the data out of the XML, however, I am unable to get it to format correctly. The error seems to be with the json_encode not adding the curly braces to the outputted date. This is the code I have so far:
<?php
$url = 'http://cloud.tfl.gov.uk/TrackerNet/LineStatus';
if(!$xml = simplexml_load_file($url))
{
die("No xml for you");
}
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
echo $line->Line['Name'];
echo $line->Status['Description'];
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
?>
The problem is that you're not storing the name and description into the array.
Try this:
foreach ($xml->LineStatus as $line)
{
$linestatus[] = array('name' => $line->Line['Name']);
$linestatus[] = array('description' => $line->Line['Description']);
}
Demo!
The echos are screwing everything up. I think you intend to append to linestatus which remains empty per your code.
$linestatus[] = array(
"name" => $line->Line['Name'],
"description" => $line->Status['Description']
);
You also need to use echo instead of print_r to actually emit the JSON.
You are declaring $linestatus as an array, then never put anything in it before finally encoding it and trying to output it. Of course it won't work as expected! Instead, you should be populating it with values:
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
$linestatus[] = $line->Line;
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
I am trying to figure out how to fwrite into a .php file with variables given through $_POST, or $_GET, supplied by the user to set variables and such. So, how would I go about getting the below code to work so that instead of fwriting the code, insert a $_GET variable for example, or in the below description, being $derp.
<?php
$derp = "working!";
$something = '<?php echo "Well Thats {$derp}' ?>';
$file = fopen("worked.php","w");
if (fwrite($file,$something) > 0) {
echo "Fwrite Successful!";
}
fclose($file);
?>
Although this use case looks very weird the following should work:
$data = array('<?php');
foreach ($_REQUEST as $key => $value) {
$data[] = "\$$key = \"$value\";";
}
$data[] = '?>';
$data = join("\n", $data);
file_put_contents('/path/to/file.php', $data);
Beware: This code imposes several security risks.
WTF is going on here?
The above code iterates through all array elements of $_GET and $_POST, combined.
By that it creates an array of lines to be written to a file.
This array will then be join()ed into a string by using the NEWLINE ascii character as the glue.
Assuming this script is called with the following query string:
?foo=bar&bar=baz
The file /path/to/file.php will then contain (file_put_contents):
<?php
$foo = "bar";
$bar = "baz";
?>
The example above does not support nested query parameters like foo[bar]=baz.
I'm currently stuck on what I thought would be an easy solution... I'm working with PHPFileNavigator, and the only thing I'm stuck on is how I can echo the Title that is returned to an array on a separate file. Every time a file is created/edited for an uploaded file, it generates the following file below when a title is added to the file.
Update
Generally all I'm wanting to do is return the one Array value from my destination file which in this case would be from the 'titulo' key, and then print it back to my source file.
Destination File
<?php
defined('OK') or die();
return array(
'titulo' => 'Annual 2011 Report',
'usuario' => 'admin'
);
?>
Source File
<?php
$filepath="where_my_destination_file_sits";
define('OK', True); $c = include_once($filepath); print_r($c);
?>
Current Result
Array ( [titulo] => Annual 2011 Report [usuario] => admin )
Proposed Result
Annual 2011 Report
All I'm wanting to find out is how can I echo this array into a variable on another PHP page? Thanks in advance.
Assuming your file is saved at $filepath
<?php
define('OK', True);
$c = include_once($filepath);
print_r($c);
If you know the file name and file path, you can easily capture the returned construct of the php file, to a file.
Here is an example:
$filepath = 'path/to/phpfile.php';
$array = include($filepath); //This will capture the array
var_dump($array);
Another example of include and return working together: [Source: php.net]
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>
Update
To only print a item from the array, you can use the indices. In your case:
<?php
$filepath="where_my_destination_file_sits";
define('OK', True); $c = include_once($filepath); print_r($c);
echo $c['titulo']; // print only the title
?>
First we have a file(you want initiate array in it ) first.php
(you can also act profissionaler and play with parameters,with any parameter function pass different type or different array)
function first_passing() {
$yourArray=array('everything you want it's be');
return $yourArray;
}
And in second.php
require 'yourpath/first.php' (or include or include_once or require_once )
//and here just call function
$myArray=first_passing();
//do anything want with $myArray
To print/echo an array in PHP you have to use print_r($array_variable) and not echo $array