I have the following code:

$filename = "raw_data.txt";
$fp = @fopen("$filename", 'r');
if ($fp){
    $array = explode("(.)", fread($fp, filesize($filename)));
}
for ($i=0; $i<sizeof($array); $i++){
    //name1 name2 name3 name4
}

So what I want to do is initialize variables with $name and the current $i value
Thanks in advance

Why do you want to do that? Generally speaking, this is a bad plan. You are far better of creating an array containing all your names and using them like $array["name1"].

Also, you can use file_get_contents instead of the whole fopen/fread/fclose routine.

$filename = "raw_data.txt";
$filedata = file_get_contents($filename);
$raw_array = explode("(.)", $filedata);

$data = array();
for ($i = 0; $i < sizeof($raw_array); ++$i){
    $data["name" . $i] = $raw_array[$i];
}

Now you have an array named $data that you can use like: $data["name1"], rather than having a variable named $name1. They work the same, this is just cleaner...

Just for the record, if you change the inside of the loop to this, you get what you originally asked for

${"name" . $i} = $raw_array[$i];

It dynamically creates the variable using the string inside the {} bracekts as the name.

I think what youre asking is for this:

This is assuming your text document is split by "." as you have above, so...
Joe Cren(.)Ryan Troop(.)Eddie Vedder(.)Led Zepplin(.) //or something similar

if you do:

$array = explode("(.)", fread($fp, filesize($filename)));
//this array is populated ['Joe Cren', 'Ryan Troop', 'Eddie Vedder', 'Led Zepplin']

To use those, I can do:

foreach($array as $key=>$value)
{
//do something with a name, one at a time
echo "Name ".$key.": ".$value."<br>";
}

The above will output:
Name 0: Joe Cren
Name 1: Ryan Troop
Name 2: Eddie Vedder
Name 3: Led Zepplin

Alternatively, you can access the items directly using:
echo $array[0]; //will output: Joe Cren

and we can make a for loop as you have done:

for($i=0; $i<count($array);$i++)
{

echo "Name ".($i+1).": ".$array[$i]."<br>";

}

The above will output:
Name 1: Joe Cren
Name 2: Ryan Troop
Name 3: Eddie Vedder
Name 4: Led Zepplin

Hope that clarifies for you.

Ryan

EDIT: I posted at the same time as the above. The above method is much more elegant and easier to read.

Member Avatar for diafol

Give an example of the file contents and an example of what you need with regard to variables. This is a little confusing.

Thanks Atli your code worked great. The reason I didn't use arrays is because there are already tens of thousands of lines of code and I didn't want to go through them all. The only problem I have now is that I cant get the data if I'm in a different folder. I have index.php in the root and have apps.php (where the variable variables are initialized) that is two levels deep.

How are you trying to get the data? If you use the inclue command to incldue the apps.php into the index.php, you just have to specify the relative path

include "path/to/apps.php";

It just takes in Unix style paths, exactly like you'd write them in a Unix terminal.

@Atli That's what I have done.

include 'apps/page1/apps.php;

I can only echo if I have a file in the same folder. Do I need to set something global?

bump?

@JameB, It's rarely a good idea to include files using the HTTP protocol, and it's even rarer that you'd want to include a text file using the include command. Typically you'd want to read such files in using file_get_contents or a fopen handler.

I can only echo if I have a file in the same folder. Do I need to set something global?

No, the location of the included PHP file shouldn't matter at all in that regard. It's more likely that something is going wrong in the included code because of the changed path.

Keep in mind that when you incldue a PHP file into another PHP file, the currrent working directory (CWD) doesn't change. That is, the CWD will remain on the path to the file that does the including, even for the code inside the included file.

So, say that you have three files, structured like this:

/var/www/ (web-root)
   index.php
   apps/
       page1/
           app.php
           data.txt

You could write the two page1 files like this without having a problem:

// apps/page1/data.txt

first: Value for the first var.
second: And the value for the second var.
third: Etc...

And:

<?php
// apps/page1/app.php

$file_path = "data.txt";
$contents = file_get_contents($file_path);
$lines = preg_split("/\n\r?/", $contents);

foreach ($lines as $line) {
    $parts = explode(":", $line);
    if (count($parts) == 2 && !empty($parts[0]) && !empty($parts[1])) {
        ${"name_" . ($parts[0])} = trim($parts[1]);
    }
}

If you call the apps.php file by itself, there is no problem. The code generates the name_first, name_second, and name_third variables fine, and you could use them in that file as you see fit.

However, if you included the app.php into the index.php file two directories lower in the hierarchy, then you've got a problem. The CWD of the index script would be /var/www, so when you call file_get_contents("data.txt") in the app.php file, then you are actually trying to read: /var/www/data.txt, as opposed to the file in the same directory as that script.

You need to be careful about these types of things when dealing with included files. One way is to use the __DIR__ constant, which is always set to the directory of the script it's in.

$file_path = __DIR__ . "/data.txt";

This way you can define the path relative to the app.php file, no matter where it's included.

Note that the above will only work in PHP 5.3 and higher. In older versions, you can get the same results with the __FILE__ constant and the dirname function

$file_path = dirname(__FILE__) . "/data.txt"

Beautiful. You saved me so much time Atli. I ended up using

$filename = dirname(__FILE__) . "/raw_data.txt";

And everything worked perfectly. Thanks again!

@JameB, It's rarely a good idea to include files using the HTTP protocol, and it's even rarer that you'd want to include a text file using the include command. Typically you'd want to read such files in using file_get_contents or a fopen handler.

Ah I didn't read all of the posts... but yeah in this case it's not the best way to do what OP is trying to do. But I was wondering, did you say that for any other reasons?

But I was wondering, did you say that for any other reasons?

About not using HTTP with PHP includes? Yea. There are a few good reasons why you'd want to avoid that.

  • In order for that to work, both the allow_url_fopen and allow_url_include directives have to be enabled in the PHP config. (The allow_url_enclude directive is Off by default.)

  • Enabling allow_url_include imposes a major code-injection vulnerability onto any application running on the server. It's far too easy for a PHP developer to accidentally introduce a way for an attacker to execute code loaded from a remote resource when that directive is enabled. You'd need to be extremely careful with all your include and require statements.

  • PHP files that are included by HTTP operate in a differente scope than files included using normal file paths. This, too, is a security restriction; not allowing remote code to access or manipulate variables in the scope of the calling code. - As an example, if the example app I described in my last post were to include the app.php file using a HTTP path rather than a file path, the app.php code could execute perfectly fine and create those variables. However the calling code would never be able to use them. PHP wouldn't allow it.

  • It can negatively affect the performance of the PHP application. A HTTP request is FAR slower than a simple local file IO operation.

  • The HTTP request, even if it's just a request for a PHP file on the localhost, will have to return PHP code. On a PHP enabled server, that won't happen. Instead it will return the result of the PHP code execution.

commented: Cool, thanks! +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.