Php parse variable line by line

Php php read variable line by line

In that case you can use a generic loop: Now if you feed this with on standard input and then detach the input (by pressing CTRL-D for example), then the output you get is: The same code is obviously usable with input redirection, so you can feed a file into the script which makes detaching the standard input obsolete. This should do what you’re looking for: Solution 1: Consider this example: When executing and feeding it with you will get this output: Bottom line: you certainly can use loops or similar for the purpose and this can shorten your code a bit.

PHP Performing action on a variable line by line

Your question is similar to this one although one might argue about whether the answers are understandable for a beginner. This should do what you’re looking for:

 // Or get the 5th line $fifth_line = $lines[4]; // Or iterate using an index for($line = 0; $line

Read text from file via .php and store parts in variable, Your code would look like something like this:

Читайте также:  Вертикально по середине css

Simple way to read variables on different lines from STDIN?

When executing and feeding it with

array(4) < [0] =>int(1) [1] => string(3) "foo" [2] => string(3) "bar" [3] => int(4) > 

Bottom line: you certainly can use loops or similar for the purpose and this can shorten your code a bit. Most of all it simplifies its maintenance. However if you want to specify a format to read with each iteration, then you do need to specify that format somewhere. That is why shortening the code is limited.

Things are different if you do not want to handle different types of input formats. In that case you can use a generic loop:

Now if you feed this with

on standard input and then detach the input (by pressing CTRL-D for example), then the output you get is:

array(3) < [0] =>int(1) [1] => int(2) [2] => int(3) > 

The same code is obviously usable with input redirection, so you can feed a file into the script which makes detaching the standard input obsolete.

If you can in your code, try to implement a array :

fscanf(STDIN, "%d\n", $n); $num=array(); while($n--) < fscanf(STDIN, "%d\n", $num[]); >print_r($num); 

PHP read from file line by line, declare as variable, then use in, 1st issue: Likely, your file is being read in order, but your query is finding all of those rows. You can see if this is happening by adding

PHP read from file line by line, declare as variable, then use in MySQL query as WHERE column_name equals variable

1st issue: Likely, your file is being read in order, but your query is finding all of those rows. You can see if this is happening by adding the line number to your output. Try changing your foreach to foreach($lines as $lineNum => $line) < and your output to $out = $lineNum.implode(',', $row)."\n"; If you have the same lineNum for 60025909170 and 0000060025909170, then you know that the query is matching both.

2nd issue: You just need to add a flag of FILE_APPEND to the file_put_contents. Like this: file_put_contents($outfile, $out, FILE_APPEND) ;

Compare first word of each line of a file to a variable in php,

PHP — Read a text file and use each line value sequentially in POST requests

Try this, if i am right your must contain the id field

 null ); foreach( $lines as $line ) < $line = trim( $line ); $post["id"] = $line; $twitter = new TwitterAPIExchange( $settings ); $response = $twitter->buildOauth( sprintf( $url, $line ), "POST" ) ->setPostfields( $post ) ->performRequest(); $response = json_decode( $response ); if ( !$response ) < echo "Empty response"; break; >var_dump( $response ); > ?> 

Use fopen to read the file and then inside the loop you can create the URL and send a POST request, like so:

$f = fopen("file.txt", "r"); while(!feof($f)) < $url = "https://api.twitter.com/1.1/statuses/destroy/" . trim($f) . ".json"; $requestMethod = 'POST'; $postfields = array( ); $twitter = new TwitterAPIExchange($settings); $twitter->buildOauth($url, $requestMethod) ->setPostfields($postfields) ->performRequest(); > 

Something along these lines should help you solve that issue

 $IDfile = "file.txt"; $lines = file($IDfile); foreach($lines as $line_num => $line) < echo sending request for $line; $url = "https://api.twitter.com/1.1/statuses/destroy/" .$line . ".json"; $requestMethod = 'POST'; $postfields = array( ); $twitter = new TwitterAPIExchange($settings); $twitter->buildOauth($url, $requestMethod) ->setPostfields($postfields) ->performRequest(); > 

Reading stdin line by line, According to php.net this should work $line=trim(fgets(STDIN));. Otherwise you could use this $handle=$fopen(‘file.ext’);

Источник

Parsing inline variables from string from file in php

In a related post, php string variables in gettext, the answer seemed to indicate that you just CAN’T use string variables, and that you would need to hardcode the variable name, $myText, into the poedit file itself. Is there a way to make it parse the variables, or alternatively is there another way of reading the lines that allows for parsing the inline variables?

Parsing inline variables from string from file in php

I’m localizing a website that I’ve built. I’m doing this by having a .lang file read and each line (syntax: key=string) is placed in a variable depending on the chosen language.

This array is then used to place the strings in the correct places.

The problem I’m having is that certain strings need to have hyperlinks in the middle of them for example someplace I’ve put my name that links to my contact page. Or a lot of the readouts of the website need to be in the strings.

To solve this I’ve defined a variable that holds the html + Forecaster + html, and the localization file contains the $Forecaster variable in the string.

The problem with this as I promptly discovered is that it stubbornly refuses to parse the inline variables in the strings from the file.

Instead it prints the string and variable name as it looks in the file.

And I have yet to find a way to make it parse the variables.

For example «Heating up took $str_time» would be printed on the page exactly like that, instead of inputting the previously defined value of $str_time.

I currently use fopen() and fgets() to open and read the lines. I then explode them to separate the key and the string and then place these into the array.

Is there a way to make it parse the variables, or alternatively is there another way of reading the lines that allows for parsing the inline variables?

The code that gets the line and converts it to the array looks like this:

(It obviously loops through the lines)

#list($key, $string) = explode('=', $line); $key = strtok($line, '='); $string = strtok('='); $local[$key] = $string; $counter++; echo $local[$key] . "
";

The counter is unused and the echo is for testing.

A line from the .lang file looks like this:

fuel.results.heatup.timeused=Heating up took $str_time 

I would call the array where I want the string like this:

$local['fuel.results.heatup.timeused'] 

As you can see I’ve tried both explode and strtok but it hasn’t made a difference.

Personally I’d write your text file in JSON format to make it easier to pull data out.

Here is a solution directly from the php manual: http://nz2.php.net/manual/en/function.eval.php

$string = 'cup'; $name = 'coffee'; $str = 'This is a $string with my $name in it.'; echo $str. "\n"; eval("\$str = \"$str\";"); echo $str. "\n"; 

It is worth noting that eval() can be very dangerous used in the wrong way so make sure you’re code is very secure E.g. if someone altered your txt file with real PHP code they could execute it directly on the server.

Another approach would require you to know all your variable names and could then do something like:

$str = 'Heating up took $str_time'; echo 'str=' . str_replace('$str_time', $str_time, $str); 
$str = 'Heating up took $str_time as well as $other_value'; $vars = Array('str_time', 'other_value'); foreach($vars as $varName) < $str = str_replace('$' . $varName, $$varName, $str); >echo 'str=' . $str; 

If you not know all the variable name, you can use this example, without eval() . It is indicatred to avoid eval() .

$str = 'fuel.results.heatup.timeused=Heating up took $str_time'; $str_time = 'value'; if(preg_match('/\$([a-z0-9_]+)/i', $str, $v)) < $vname = $v[1]; $str = str_replace('$'.$vname, $$vname, $str); >echo $str; // fuel.results.heatup.timeused=Heating up took value 

PHP: display value of PHP variables inside a string, Since you use single quotes you cannot add variables inside the string unless you use a curly brace or a dot. Note: using the double quotations method is faster than using the using curly braces or a dot. If you want to echo a variable and use a single quoted string in php you have to «glue» the parts together.

Can I load a file in PHP as a string with inline variables?

I’ve got a simple (but not tiny) template for some HTML, complete with inline variables. I’d like to pull that out as a separate file, and have the ability to switch in other template files. Is there a way to load a file into a string, but have it process inline variables?

$thing="complete sentence"; $test= 

What I want is something like this:

// "test.html"  

This will get parsed as a $thing.

// "index.php" $thing="complete sentence"; $test=file_get_contents("test.html"); echo $test; // This will get parsed as a complete sentence.

How do I achieve this, preferably without a templating library?

This code uses preg_replace_callback to check what is variable. But, because we are in function , we cannot directly access script variables. We have to use $_GLOBALS variable which contains every script variable. $matches[1] contains name of matched variable.

Something like this should work.

// "test.php" This will get parsed as a %s. // "index.php" $thing="complete sentence"; $test=file_get_contents("test.php"); printf($test, $thing); 

You can use include to simply load the file as if it were part of the calling code.

If you cannot include for some reason, you can read the file contents and eval it.

$content = file_get_contents("included_file.php"); eval($content); 

As pointed by NikiC, your file test.html doesn't have valid PHP. You would have to change it so include can work. Your test.html should have this content:

  

This will get parsed as a .

And eval would not work with this code, as this is not pure PHP code, it is HTML code with PHP inside it. If your included file has just PHP code, it would work fine.

String in PHP | Four Different Types of String Declaration, strtolower, strtoupper, strlen, explode, substr, str_replace, strops, sha1, md5, str_word_count, ucfirst, lcfirst are the string functions. These string functions are very helpful in creating projects or Programs. “strtolower” converts all the string characters to the lowercase letters whereas “strtoupper” will convert them to …

Php string variables with foreach using gettext

It seems that the way to make your text echo out using gettext is to use the form:

Of course, when you are using variables you can't just add quotation marks, since then the variable name would be outputted as a literal, e.g.:

In a related post, php string variables in gettext, the answer seemed to indicate that you just CAN'T use string variables, and that you would need to hardcode the variable name, $myText, into the poedit file itself. Of course, this is not optimal, but it could work.

What can't work, however, is when you have a foreach loop that spits out a php variable that could be defined hundreds of times. If you have:

and count($variables) > 100, or even 10, this workaround will be prohibitive. Is there a better way??

xgettext (or poedit ) is effectively a "static analyser", meaning, it doesn't run your code, it just finds all of the _() functions, and assumes that whatever is in it is a string to be translated.

So, if you do: _('Hello, world')
Then the string Hello, world will end up in your .po file.

If you do: _("Hello, $planet")
Then the string Hello, $planet will end up in your .po file.

This is often a good thing, since it allows us to remove (some) redundancy in your translation files. If we would have 3 planets, then we would need four translation strings; one for hello, $planet , and one for each planet.
If we would like to add bye, $planet , then we only need to add one extra translation string, and not 3.

Just wanted to make sure you understood that 🙂 Now, more specificity on the subject of your question:

you would need to hardcode the variable name, $myText, into the poedit file itself. Of course, this is not optimal, but it could work.

This won't work, since all $myText variables will resolve to the same translation string. I doubt that this is what you want?

Where are your variables coming from? If they're from a database or 3rd-party API you may want to look at a slightly different solution, such as scanning your database for translation strings, or fetching all strings from the 3rd-party API.
If you put those strings in your .po file, using _($var) will work fine, because the lookup itself is done at runtime.

Another possible solution is to make your own function, let's call it v_() (v for variable). At runtime, this function reads the contents of a .po file (or perhaps a database, which is later converted to a .po file), and if the string doesn't yet exists, it is inserted.

This might look something like this:

Because this is executed at run-time , we know the contents of the string.
In this example we use a $translation_mode variable so this code has only minimal overhead on production machines.

Php fill string variable Code Example,

Источник

Оцените статью