Jump to content

Recommended Posts

Hello,

 

The plan is to get variables from a file and store them in an array. note that we don't know what variables the target file may have. For example the target file could be like this:

 

<?php
$a = 2;
$b = 4;
$c = array(1, 2, 3);
?>

 

The result must be a variable like this:

 

<?php
$result = array(
   'a' => 2,
   'b' => 4,
   'c' => array(1, 2, 3),
);
?>

 

I have coded a solution. But I'm wondering if there could be easier ways I'm missing. So possible ways:

 

1. Get the file content, parse it line by line and possibly divide it by ; sign and start interpreting. (This is what I'm coding atm)

2. Include the file and compare the new variables to the ones before the include() which looks rather nasty.

 

* I can't change the format of the target file. It's just a php script.

* If your way requires a complicate regex, I'd be grateful if you show me the regex code.

 

Thanks for your time.

What is nasty about getting the defined variables and comparing them? Parsing your file is a lot uglier in my opinion...

 

I would do something like:

<?php
$vars = get_defined_vars();
include('your_php_file.php');
$vars_in_your_php_file = array_diff_assoc(get_defined_vars(), $vars);

 

This will have a small issue though. Having the same variable with same name and value already defined before including your vars, the var will not be present in the resulting array.

Thanks for the replies.

 

@johnny86,

I will have a problem with variables already defined. Other than that, that would be a nice solution. I said nasty because in case there are thousands of variables already defined.

 

@requinix,

I came across parse_ini_file but my problem is that I can't change the target file. It is a php script and must stay as it is.

Then you should create a class in which you include the files with the variables. The included file will inherit the scope of the class. Thay way you can use the objects scope to extract the variables from the file.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.