Get Array from PHP file and use in another PHP file - php

So i am having trouble getting an array from one PHP file to another.
In my first file (file1.php) i got following code:
print_r($order->delivery);
It will get visible when using echo of course, and it outputs the right things. It gives me an array with order information. Now i got another PHP file I need to use this information in.
What i tried so far is including file1.php to file2.php and then echo the array... But the result is empty.
require_once('path/file1.php');
echo print_r($order->delivery);
And i tried echo my array directly in file1.php adding a div like this
echo "<div id='test'>" . print_r($order->delivery, true) . "</div>";
And then getting the inner HTMl of the div with DOM
$dom = new DOMDocument();
$dom->loadHTML("mypageurl");
$xpath = new DOMXPath($dom);
$divContent = $xpath->query('//div[id="test"]');
if($divContent->length > 0) {
$node = $divContent->item(0);
echo "{$node->nodeName} - {$node->nodeValue}";
}
else {
// empty result set
}
Well... none of it works. Any suggestions?

You have to set a variable or something, not echoing it.
file1.php:
$delivery = $order->delivery;
file2.php
include('path/file1.php');
echo "<div id='test'>" . (isset($delivery['firstname']) ? $delivery['firstname'] : '') . "</div>";
Or you use the $object directly if it is set in file1.php
file2.php
include('path/file1.php');
echo "<div id='test'>" . (isset($order->delivery['firstname']) ? $order->delivery['firstname'] : '') . "</div>";

You can do this by using $_SESSION or $_COOKIE, See here for more detail; PHP Pass variable to next page

Be careful at the variable scope. See this link: http://php.net/manual/en/language.variables.scope.php
And try this code please:
require_once('path/file1.php');
global $order;
print_r($order->delivery);
Defining $order as global should fix your issue.

You could return an array in a file and use it in another like this:
<?php
/* File1.php */
return array(
0,1,2,3
);
-
<?php
/* File2.php */
var_dump(require_once('File1.php'));

Related

Echo / printr inside variable

I have inside a php file a variable called $html which is gathering lots of information like this:
$html .= something;
$html .= something else;
etc
and in another file its being echoed like this:
echo $this->html;
What i need is at first file that $html .= is used to echo something like this:
echo '<pre>';
echo 'printr($this->cart)';
echo '</pre>';
But i need those 3 lines to be included in $html variable in order to be echoed at second file through: echo $this->html;
Any ideas?
Thank you in advance
use var_export() function for including your array in to $html variable
In php file just assign what you want to assign to $html variable then you can print it anywhere by it's variable name .
for example :
$html="";
$html .="your text";
$html .="any dynamic values";
then echo this like
echo $html;
if you are using function then simply call a function and pass your all code within function then called function from anywhere.

Using PHP to determine what HTML to write out

This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>

PHP include HTML and echo out variable

I am working on a script with templates. So I have this PHP code:
<?php
$string = "TEST";
echo(file_get_contents('themes/default/test.html'));
?>
And I have this HTML (the test.html file):
<html>
<p>{$string}</p>
</html>
How can I make PHP actually display the variable inside the curly brackets? At the moment it displays {$string}.
P.S:
The string might also be an object with many many variables, and I will display them like that: {$object->variable}.
P.S 2: The HTML must stay as it is. This works:
$string = "I'm working!"
echo("The string is {$string}");
I need to use the same principle to display the value.
You can use the following code to achieve the desired result:
<?php
$string = "TEST";
$doc = file_get_contents('themes/default/test.html'));
echo preg_replace('/\{([A-Z]+)\}/', "$$1", $doc);
?>
P.S. Please note that it will assume that every string wrapped in { }
has a variable defined. So No error checking is implemented in the code above. furthermore it assumes that all variables have only alpha characters.
If it is possible to save your replacees in an array instead of normal variables you could use code below. I'm using it with a similar use case.
function loadFile($path) {
$vars = array();
$vars['string'] = "value";
$patterns = array_map("maskPattern", array_keys($vars));
$result = str_replace($patterns, $vars, file_get_contents($path));
return $result;
}
function maskPattern($value) {
return "{$" . $value . "}";
}
All you PHP must be in a <?php ?> block like this:
<html>
<p><?php echo "{" . $string . "}";?></p>
</html>
If you know the variable to replace in the html you can use the PHP function 'str_replace'. For your script,
$string = "TEST";
$content = file_get_contents('test.html');
$content = str_replace('{$string}', $string, $content);
echo($content);
It's simple to use echo.
<html>
<p>{<?php echo $string;?>}</p>
</html>
UPDATE 1:
After reading so many comments, found a solution, try this:
$string = "TEST";
$template = file_get_contents('themes/default/test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace('{$string}',$string,$template);
echo $page;

change variable with GET method

I have a page test.php in which I have a list of names:
name1: 992345
name2: 332345
name3: 558645
name4: 434544
In another page test1.php?id=name2 and the result should be:
332345
I've tried this PHP code:
<?php
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("/test.php");
$xpath = new DOMXpath($doc);
$elements = $xpath->query("//*#".$_GET["id"]."");
if (!is_null($elements)) {
foreach ($elements as $element) {
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo $node->nodeValue. "\n";
}
}
}
?>
I need to be able to change the name with GET PHP method in test1.pdp?id=name4
The result should be different now.
434544
is there another way, becose mine won't work?
Here is another way to do it.
<?php
libxml_use_internal_errors(true);
/* file function reads your text file into an array. */
$doc = file("test.php");
$id = $_GET["id"];
/* Show your array. You can remove this part after you
* are sure your text file is read correct.*/
echo "Seeking id: $id<br>";
echo "Elements:<pre>";
print_r($doc);
echo "</pre>";
/* this part is searching for the get variable. */
if (!is_null($doc)) {
foreach ($doc as $line) {
if(strpos($line,$id) !== false){
$search = $id.": ";
$replace = '';
echo str_replace($search, $replace, $line);
}
}
} else {
echo "No elements.";
}
?>
There is a completely different way to do this, using PHP combined with JavaScript (not sure if that's what you're after and if it can work with your app, but I'm going to write it). You can change your test.php to read the GET parameter (it can be POST as well, you'll see), and according to that, output only the desired value, probably from the associative array you have hard-coded in there. The JavaScript approach will be different and it would involve making a single AJAX call instead of DOM traversing using PHP.
So, in short: AJAX call to test.php, which then output the desired value based on the GET or POST parameter.
jQuery AJAX here; native JS tutorial here.
Just let me know if this won't work for your app, and I'll delete my answer.

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Is there a Shortcut for
echo "<pre>";
print_r($myarray);
echo "</pre>";
It is really annoying typing those just to get a readable format of an array.
This is the shortest:
echo '<pre>',print_r($arr,1),'</pre>';
The closing tag can also be omitted.
Nope, you'd just have to create your own function:
function printr($data) {
echo "<pre>";
print_r($data);
echo "</pre>";
}
Apparantly, in 2018, people are still coming back to this question. The above would not be my current answer. I'd say: teach your editor to do it for you. I have a whole bunch of debug shortcuts, but my most used is vardd which expands to: var_dump(__FILE__ . ':' . __LINE__, $VAR$);die();
You can configure this in PHPStorm as a live template.
You can set the second parameter of print_r to true to get the output returned rather than directly printed:
$output = print_r($myarray, true);
You can use this to fit everything into one echo (don’t forget htmlspecialchars if you want to print it into HTML):
echo "<pre>", htmlspecialchars(print_r($myarray, true)), "</pre>";
If you then put this into a custom function, it is just as easy as using print_r:
function printr($a) {
echo "<pre>", htmlspecialchars(print_r($a, true)), "</pre>";
}
Probably not helpful, but if the array is the only thing that you'll be displaying, you could always set
header('Content-type: text/plain');
echo '<pre>' . print_r( $myarray, true ) . '</pre>';
From the PHP.net print_r() docs:
When [the second] parameter is set to TRUE, print_r() will return the information rather than print it.
teach your editor to do it-
after writing "pr_" tab i get exactly
print("<pre>");
print_r($);
print("</pre>");
with the cursor just after the $
i did it on textmate by adding this snippet:
print("<pre>");
print_r(\$${1:});
print("</pre>");
If you use VS CODE, you can use :
Ctrl + Shift + P -> Configure User Snippets -> PHP -> Enter
After that you can input code to file php.json :
"Show variable user want to see": {
"prefix": "pre_",
"body": [
"echo '<pre>';",
"print_r($variable);",
"echo '</pre>';"
],
"description": "Show variable user want to see"
}
After that you save file php.json, then you return to the first file with any extension .php and input pre_ -> Enter
Done, I hope it helps.
If you are using XDebug simply use
var_dump($variable);
This will dump the variable like print_r does - but nicely formatted and in a <pre>.
(If you don't use XDebug then var_dump will be as badly formated as print_r without <pre>.)
echo "<pre/>"; print_r($array);
Both old and accepted, however, I'll just leave this here:
function dump(){
echo (php_sapi_name() !== 'cli') ? '<pre>' : '';
foreach(func_get_args() as $arg){
echo preg_replace('#\n{2,}#', "\n", print_r($arg, true));
}
echo (php_sapi_name() !== 'cli') ? '</pre>' : '';
}
Takes an arbitrary number of arguments, and wraps each in <pre> for CGI requests. In CLI requests it skips the <pre> tag generation for clean output.
dump(array('foo'), array('bar', 'zip'));
/*
CGI request CLI request
<pre> Array
Array (
( [0] => foo
[0] => foo )
) Array
</pre> (
<pre> [0] => bar
Array [1] => zip
( )
[0] => bar
[0] => zip
)
</pre>
I just add function pr() to the global scope of my project.
For example, you can define the following function to global.inc (if you have) which will be included into your index.php of your site. Or you can directly define this function at the top of index.php of root directory.
function pr($obj)
{
echo "<pre>";
print_r ($obj);
echo "</pre>";
}
Just write
print_r($myarray); //it will display you content of an array $myarray
exit(); //it will not execute further codes after displaying your array
Maybe you can build a function / static class Method that does exactly that. I use Kohana which has a nice function called:
Kohana::Debug
That will do what you want. That's reduces it to only one line. A simple function will look like
function debug($input) {
echo "<pre>";
print_r($input);
echo "</pre>";
}
function printr($data)
{
echo "<pre>";
print_r($data);
echo "</pre>";
}
And call your function on the page you need, don't forget to include the file where you put your function in for example: functions.php
include('functions.php');
printr($data);
I would go for closing the php tag and then output the <pre></pre> as html, so PHP doesn't have to process it before echoing it:
?>
<pre><?=print_r($arr,1)?></pre>
<?php
That should also be faster (not notable for this short piece) in general. Using can be used as shortcode for PHP code.
<?php
$people = array(
"maurice"=> array("name"=>"Andrew",
"age"=>40,
"gender"=>"male"),
"muteti" => array("name"=>"Francisca",
"age"=>30,
"gender"=>"Female")
);
'<pre>'.
print_r($people).
'</pre>';
/*foreach ($people as $key => $value) {
echo "<h2><strong>$key</strong></h2><br>";
foreach ($value as $values) {
echo $values."<br>";;
}
}*/
//echo $people['maurice']['name'];
?>
I generally like to create my own function as has been stated above. However I like to add a few things to it so that if I accidentally leave in debugging code I can quickly find it in the code base. Maybe this will help someone else out.
function _pr($d) {
echo "<div style='border: 1px solid#ccc; padding: 10px;'>";
echo '<strong>' . debug_backtrace()[0]['file'] . ' ' . debug_backtrace()[0]['line'] . '</strong>';
echo "</div>";
echo '<pre>';
if(is_array($d)) {
print_r($d);
} else if(is_object($d)) {
var_dump($d);
}
echo '</pre>';
}
You can create Shortcut key in Sublime Text Editor using Preferences -> Key Bindings
Now add below code on right-side of Key Bindings within square bracket []
{
"keys": ["ctrl+shift+c"],
"command": "insert_snippet",
"args": { "contents": "echo \"<pre>\";\nprint_r(${0:\\$variable_to_debug});\necho \"</pre>\";\ndie();\n" }
}
Enjoy your ctrl+shift+c shortcut as a Pretty Print of PHP.
Download AutoHotKey program from the official website: [https://www.autohotkey.com/]
After Installation process, right click in any folder and you will get as the following image: https://i.stack.imgur.com/n2Rwz.png
Select AutoHotKey Script file, open it with notePad or any text editor Write the following in the file:
::Your_Shortcut::echo '<pre>';var_dump();echo '</pre>';exit();
the first ::Your_Shortcut means the shortcut you want, I choose for example vard.
Save the file.
Double-click on the file to run it, after that your shortcut is ready.
You can test it by write your shortcut and click space.
For more simpler way
echo ""; print_r($test); exit();

Categories