Marcel Wasilewski
Marcel Wasilewski

Reputation: 2679

Get Array from PHP file and use in another PHP file

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?

Upvotes: 4

Views: 8319

Answers (4)

Marcel Burkhard
Marcel Burkhard

Reputation: 3523

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'));

Upvotes: 1

Ciprian Stoica
Ciprian Stoica

Reputation: 2439

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.

Upvotes: 1

Brad Fletcher
Brad Fletcher

Reputation: 3593

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

Upvotes: 1

KiwiJuicer
KiwiJuicer

Reputation: 1982

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>";

Upvotes: 2

Related Questions