This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Help me parse this file with PHP
I need to extract some text from a text file.suppose there is a text file in http://site.com/a.txt
And the contents of that file is like this:
var $name= 'name1';
var $age= 'age2';
var $phone= 'phonenumber';
var $a= 'asd';
var $district= 'district23';
How can I get the values of this text file (name1,age2,phonenumber,asd,district) in separate echo.
Use the file function to read the file into an array. Then loop through the array and each line in the file will be another element in the array. So make sure your file has line-breasks between the data.
Of course the best would be to have ready PHP code in a .php file which would then be included with the include function.
Organize the content of your text file like this : name1,age2,phonenumber,asd,district
And do this :
// Get the content of your file
$content = file_get_contents('a.text');
// Set your values with this
list($name, $age, $phone, $a, $district) = explode(',', $content);
// Then feel free to echo wathever you want
echo 'Name ' . $name;
Use an array and encode it: http://uk.php.net/manual/en/function.json-encode.php
I recommend using a class to encapsulate your data...
So imagine having a file called "person.php" that looks like this...
class Person
{
public $Name;
public $Age;
public $Phone;
public $A;
public $District;
}
You can then use the person class as a container.
include_once('person.php');
$person = new Person();
$person->Name = 'John Doe';
$person->Age = 52;
$person->Phone= '+441234 567 890';
$person->A = 'asd';
$person->District = 'District23';
Please note that "Age" is volatile (i.e. if the object lives for too long, the age will wrong!) You could avoid this by storing date of birth and then having a getAge() function on the Person object that gives you the correct age at any point in time.
The Person class is a plain PHP object, but you could add functions that add behaviour that relates to the concept of a Person, so the getAge() function would live on the Person class.
Finally, you could then store the object wherever you like using PHP's serialize and unserialize functions. The stored string that represents your object would look like this:
O:6:"Person":5:{
s:4:"Name";s:8:"John Doe";
s:3:"Age";i:52;
s:5:"Phone";s:15:"+441234 567 890";
s:1:"A";s:3:"asd";
s:8:"District";s:10:"District23";
}
And here is how you serialize the $person to look like this:
$serializedPerson = serialize($person);
echo $serializedPerson;
And converting from a string back to a Person is easy too:
$serializedPerson = 'O:6:"Person":5:{s:4:"Name";s:8:"John Doe";s:3:"Age";i:52;s:5:"Phone";s:15:"+441234 567 890";s:1:"A";s:3:"asd";s:8:"District";s:10:"District23";}';
$newPerson = unserialize($serializedPerson);
echo $newPerson->Name;
Summary
So if you stored you data in this serialized format, it is really easy to convert it directly into a PHP object that you can use without manually parsing the strings. You could store the string in a text file if you wanted - or a data store.
Rather than giving you the solution code I'm going to break this down into steps for you.
0) write the file in a machine readable format, e.g. name,age,phonenumber
1) Read from the file line by line
2) Break each line up according to the separator you used e.g. ","
3) Read in values into variables
4) Echo out
If you're stuck on something more specific, let us know.
Related
I don't know the correct wording for this issue I am having.
I have a object returned from the database like below:
$pProvisioningFileData->m_fileContent = # Placeholders identified by '${}'
will be replaced during the provisioning
# process, only supported placeholders will be processed.
Dcm.SerialNumber = ${unit.serial_number}
Dcm.MacAddress = ${unit.mac_address}
Dcm.MinSeverity = "Warning"
Cert.TransferHttpsCipherSuite = "CS1"
Cert.TransferHttpsTlsVersion = "TLSv1"
Cert.MinSeverity = "Warning";
The curly brackets are placeholders, the problem I am facing is that when I try output all the content using either echo or print_r, all the content prints in one line however I want to display the content in the same sequence as above.
I tried using var_dump but it also gives some extra info like length and type of variable which I don't want.
So is there a simple way of doing this without using an array?
If you are outputting to browser then wrapping your var_dump in html <pre> tags is quick solution. If you outputting to console then I advise you to install some advanced debuging software. Xdebug comes to mind.
It is difficult from your question to understand exactly what you are wanting to do, but there are three ways you can print out the contents of an object. The third here, looping members, will give you more control and you can add a switch statement or other formatting to output precisely what you desire:
class unit {
var $serial_number;
var $mac_address;
}
$test = new unit;
$test->serial_number = "999";
$test->mac_address = "999.999.999.999";
/* Method 1 - print_r */
print_r($test);
print "\n\n";
/* Method 1 - var_dump */
var_dump($test);
print "\n\n";
/* Method 3 - looping members */
foreach ($test as $memberName => $member)
{
print "{$memberName}: {$member}\n";
}
I have a custom class in PHP. If I serialize the class and save it to a text file, I can't unserialize it later in another php file. When I try to call the class functions on the object I get
Call to a member function [functioname()] on a non-object...
I do include the class in both php files.
PHP File 1:
$myobject = new myclass();
$temp = serialize($myobject);
file_put_contents('serializetest.txt', $temp);
PHP File 2:
$s = file_get_contents('serializetest.txt');
$newobject = unserialize($s);
Is there some reason why a serialized class would unserialize properly?
Update
If I create an object and use it's main function I can unserialize the unrelated saved object. The class searches for criminal cases. Even though the two objects are entirely different, once I create and use the new object I can suddenly unserialize saved past objects. i.e. The below works but if I removed the first 3 lines of code it wouldn't.
$tempcase = new Expungement();
$tempcase->searchCase('4B02305986','Public',true,false);
echo "Case Number 1: " . $tempcase->caseno;
$s = file_get_contents('serializetest.txt');
echo "Serialized Data: " . $s;
$newcase = unserialize($s);
echo "Case Number 2: " . $newcase->caseno;
Have you checked content of "serializetest.txt" and value of $s?
Are file 1 and file 2 in the same directory?
Sometimes unserialize doesn't work good if you have "complicated" classes with many crossreferences.
I have some php code that extracts a web address. The object I have extracted is of the form:
WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults
Now in PHP I have called this object $linkHREF
I want to extract the id element only and put it into an array (I'm bootstrapping this process to get multiple id's)
So the command is:
$detailPagePathArray = explode("id=",$linkHREF); #Array
Now the problem is the output of this includes what comes after the id tag, so the output looks like:
echo $detailPagePathArray[0] = WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&w
echo $detailPagePathArray[1] = bf&page=1&
echo $detailPagePathArray[2] = 16123012&source=searchresults
Now the problem is obvious, where it'd firstly picking up the "id" in the "wid" marker and cutting it there, however the secondary problem is it's also picking up all the material after the actual "id". I'm just interested in picking up "16123012".
Can you please explain how I can modify my explode command to point it to the particular marker I'm interested in?
Thanks.
Use the built-in functions provided for the purpose.
For example:
<?php
$url = 'http://www.example.com?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults';
$qs = parse_url($url);
parse_str($qs['query'], $vars);
$id = $vars['id'];
echo $id; // 16123012
?>
References:
parse_url()
parse_str()
if you are sure that you are getting &id=123456 only once in your object, then below
$linkHREF = "WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults";
$str = current(explode('&',end(explode('&id', $linkHREF,2))));
echo "id" .$str; //output id = 16123012
I need to store data within a database, when I get the data from the database I need functions and variables in the string to be worked out as such.
Example
$str = "<p>Dear {$this->name},</p>"
I then store this in the database, and when I retrieve the string and run it through
eval("\$detail= \"$detail\";");
then the variable gets populated with the name. This is exactly what I needed and works fine.
The problem is I want to run a function with this variable as the parameter.
example. I would like to ucwords the variable.
I have tried:
$str = "<p>Dear {ucwords($this->name)},</p>" //just echoed {ucword(->name)},
$str = "<p>Dear {ucwords($this->name)},</p>" //Fatal error: Function name must be a string,
Am I going in the right direction?
Is this at all possible?
You don't need to keep PHP code in database. This is a bad practice and also can lead to security vulnerabilities.
Instead store in database string like this:
<p>Dear [name],</p>
And when you retrieve it you can just do:
$stringFromDb = str_replace("[name]", $this->name, $stringFromDb);
or
$stringFromDb = str_replace("[name]", ucwords($this->name), $stringFromDb);
Other common approach is to use sprintf. So you need to store in database string with %s as placeholders for values.
Example:
<p>Dear %s,</p>
and replace with
$stringFromDb = sprintf($stringFromDb, ucwords($this->name));
What you seem to be looking for is a simple templating language.
It's been a long while since I've written PHP (and I suddenly remember why...), but here's something I whipped up.
It should support both objects ($a->name) and arrays ($a["name"]) as input objects.
You can add new filters (name -> function name mapping) in $valid_filters.
$valid_filters = array("title" => "ucfirst", "upper" => "strtoupper");
function _apply_template_helper($match) {
global $_apply_template_data, $valid_filters;
$var = $match[1];
$filter = $valid_filters[trim($match[2], ':')];
$value = is_array($_apply_template_data) ? $_apply_template_data[$var] : $_apply_template_data->$var;
if($filter && !empty($value)) $value = call_user_func($filter, $value);
return !empty($value) ? $value : $match[0];
}
function apply_template($template, $data) {
global $_apply_template_data;
$_apply_template_data = $data;
$result = preg_replace_callback('/\{\{(.+?)(:.+?)?\}\}/', "_apply_template_helper", $template);
$_apply_template_data = null;
return $result;
}
How to use it:
$template = "Hello {{name:title}}, you have been selected to win {{amount}}, {{salutation:upper}}";
echo apply_template($template, array("name"=>"john", "amount" => '$500,000', "salutation" => "congratulations"));
The result:
Hello John, you have been selected to win $500,000, CONGRATULATIONS
I have found the following works,
If i contain the function within the class itself then it can be called using the following code
<p>Dear {\$this->properCase(\$this->rl_account->name)},</p>
But i would like to be able to do this now without having the database have the code as Alex Amiryan mentions earlier.
I'm writing a small script which generates some configuration for devices. I want to have separate file, where I'm storing configuration, and change some strings during printing the content of the configuration to the browser. How can I replace string in a line of the file with a variable from $_POST['somevariable']?
-- Additional info --
I have several types of devices. I want to have separate file with configuration template for each type of device. If someone want to change configuration of some type device they will change that file not php file. But in order to use this template in php I have to replace some string in that file before printing out to web page, e.g.: sys info hostname %host_name% sys info location %location% ip set %ip% the strings inbetween %% (could be any other) characters should be replaced with $_POST["host_name"], $_POST["location"], $_POST["ip"] etc. All these params gotten from the posted form.
It is advisable to use a structured file format of some sort for this purpose.
Consider using CSV, Ini, XML, JSON or YAML and use appropriate APIs to read and write them.
Another alternative would be to store the configuration in an array and then either use serialize/unserialize or use var_export/include to use it.
Very basic example:
class MyConfig
{
public static function read($filename)
{
$config = include $filename;
return $config;
}
public static function write($filename, array $config)
{
$config = var_export($config, true);
file_put_contents($filename, "<?php return $config ;");
}
}
You could use the class like this:
MyConfig::write('conf1.txt', array( 'setting_1' => 'foo' ));
$config = MyConfig::read('conf1.txt');
$config['setting_1'] = 'bar';
$config['setting_2'] = 'baz';
MyConfig::write('conf1.txt', $config);
Use SQLite. You can then query for specific data, and still have a local file. FYI - PDO quote automatically adds single quotes around a value.
$Filename = "MyDB.db";
try {
$SQLHandle = new PDO("sqlite:".$Filename);
}
catch(PDOException $e) {
echo $e->getMessage()." :: ".$Filename;
}
$SQLHandle->exec("CREATE TABLE IF NOT EXISTS MyTable (ID INTEGER PRIMARY KEY, MyColumn TEXT)");
$SQLHandle->beginTransaction();
$SQLHandle->exec("INSERT INTO MyTable (MyColumn) VALUES (".$SQLHandle->quote("MyValue").")");
$SQLHandle->exec("INSERT INTO MyTable (MyColumn) VALUES (".$SQLHandle->quote("MyValue 2").")");
$SQLHandle->commit();
$Iterator = $SQLHandle->query("SELECT * FROM MyTable ORDER BY MyColumn ASC");
unset($SQLHandle);
foreach($Iterator as $Row) {
echo $Row["MyColumn"]."\n";
}
I agree with Gordon.
If you don't follow his advice you can do something like this:
$file = file_get_contents('./conf.tpl');
$file = str_replace('%server%', 'localhost', $file);
file_put_contents('./conf.txt', $file);