In this project I am sifting through non formatted HTML code and looking for a specific value, below is a section of code from a paragraph deconstruction function. I am using preg_replace to get rid of any unneeded html code until I end up with a small array of variables delimited by the html tag. Below is the section of logic I am having a problem with. For some reason I am receiving an un-defined offset 5 error when attempting to print the 5th position of the array $pieces. I am using the explode function to create the array and have included the chunk of html code I am running explode on.
$new_broken_var = preg_replace($para_search, $para_replace, $para_subject);
$pieces = explode("<br>", $new_broken_var);
echo $pieces[5];
//upon echoing $new_broke_var I received the below html as it's value
//<font face="Arial" size="2">For 06/01/13 to 06/30/13<br>
//Report Generated: Thursday, July 11, 2013<br>Unit: 204 <br>
//Driver:<br>Owner:<br>Number of Trips: 27<br>Fuel Type: Diesel</font>
//creates an array using <br> as it's delimiter on the commented code above
//the variable we want is in position number 5 within the array. and confirmed via print_f($pieces);
It's a good practice to check whether the requested index actually exists in your array.
if (isset($pieces[5])) {
echo $pieces[5];
}
The index may not exist for various reasons, but in your case it just seems your paragraph is empty, causing explode() to return an array with a single element.
Related
I have the following code
$checkarray = unserialize(file_get_contents('serialized.txt'));
var_dump($checkarray);
foreach($checkarray as $_index => $_image )
{
echo strval($_index)." = ".var_dump($_image)."<br>";
}
var_dump(array_search('pirates_of_love_and_kingdoms.jpg',$checkarray));
var_dump(in_array('pirates_of_love_and_kingdoms.jpg',$checkarray));
the contents of 'serialized.txt' can be found here (http://textuploader.com link, not a download link, will need to copy and paste into new file if you want to use it)
the first var_dump output the array however because i have xdebug not the entire array is outputted, i'm not looking to get this fixed, it just confirms that the file was imported and unserialize correctly, the loop outputs everything in the array confirming that every value is a string (thanks to xdebug), the final 2 var_dumps are to output the results of the functions.
when i run my code, both var_dumps output false, however if i use the browser to search for the text i do find it so i know it's in the array.
I know that array_search returns the key in the array if the needle is found while in_array returns true if the needle is found and both will return false if the needle can't be found, however i do not get how neither can find it when i can confirm it's outputted in the loop and in my serialized.txt file at the same index as what is specified in the file.
i have already checked the basics, white spaces, new lines, casing in both what is outputted on the screen and in the file, can anyone explain to me what i have done wrong?
The line breaks at the end of each line are causing problems for you. Do a trim inside your foreach:
$checkarray = unserialize(file_get_contents('serialized.txt'));
var_dump($checkarray);
foreach($checkarray as $_index => $_image )
{
$checkarray[$_index] = trim($_image);
echo strval($_index)." = ".var_dump($_image)."<br>";
}
var_dump(array_search('pirates_of_love_and_kingdoms.jpg',$checkarray));
var_dump(in_array('pirates_of_love_and_kingdoms.jpg',$checkarray));
I echoing the contents of a table using foreach, the problem I am getting is the date is always at the top of the page, so when looking at my one line preview I just get the date and nothing more. If I remove the date it is fine and you can see the first line of the template. So I am trying to remove the date tag from the preview using for each.
I am using the following code, but it doesnt seem to be doing a lot, as far as I can see I have things right ?.
echo '<div class="messagerow">';
// this pulls the message from the foreach above it
$emlmsg = $row->emailformmessage;
// I am trying to remove the date by replacing it with the blank contents of this string value.
$dateremove = '';
// This is the str_replace that is supposed to remove the {date} tag along with the paragraph tags it is wrapped in.
$emlmsgfiltered = str_replace(array('<p>{date}</p>'), array($dateremove), $emlmsg);
// I then echo the filtered message here, minus the date....but its still there ??
echo $emlmsgfiltered;
echo '</div>';
Edit >>>>>>
As requested, this is the html code
<p>{date}</p>
<p>Dear {name} thankyou for your order, if you need any more oil we will be happy to provide you with a competitive quote.</p>
<p>Kind Regards</p>
{createdby}
sorry . should have been an ansewr, not a comment:
why the array around the first value in str_replace()? are you supposed to be referencing an array element
str_replace('<p>{date}</p>',$dateremove,$emlmsg)
It seems to me that '<p>{date}</p>' isn't being found. You can try to recreate the date here by typing something $date = date('Y-m-d') then '<p>'.$date.'</p>' or "<p>$date</p>"
However, the dates may not match up correctly in all cases.
You can also try to pull the date in from somewhere. That would be ideal.
I have the following CSV file:
08-0018421032;00-0018151831;G-20009429-0;G-20009429-0;0374048-0
27-001842101232;10-0018151831;G-30009429-0;G-50009429-0;7374048-0
36-0018421033232;20-0018151831;G-40009429-0;G-60009429-0;8374048-0
As you can see the separator is the ; symbol.
I then send this info to php via a jquery plugin which works perfect since I can read the file in PHP. The following code grabs the CSV file (Which is the $csvfile variable) and I can see the lines in it:
$file = fopen("upload/$csvfile", "r");
while (!feof($file) ) {
$line = fgetcsv($file, 1024,';');
print $line[0].'<br/>';
}
fclose($file);
What I need is to be able to select not only the line but on the value in it. To go to a specific value, for example in the first line the 3rd value would be G-20009429-0 and I would assign this to a php variable to be used later on.
Right now I have no idea how to grab a specific value in a line and also when I print the $line[0] it shows the values in a vertical order instead of a horizontal order. What I mean with this is that it shows the following output:
00-0018151831
10-0018151831
20-0018151831
Instead of showing me like this:
08-0018421032;00-0018151831;G-20009429-0;G-20009429-0;0374048-0
Maybe is the sleep but am stuck here. Just to repeat, the csv file is read by Php correctly since I can do a print_r on it and it shows all the lines in it. The thing is how to manipulate the information after I have the csv and how to grab a specific value in a specific line. Thank you.
$line is an array containing every element from that row. $line[0] is the first element of the row, $line[1] the second element and so on. Try var_dump($line). What you're doing is you output every first element of every row.
If you want to output every element in one line, just concatenate the array again:
echo join(';', $line);
But then that's missing the point of fgetcsv, which is specifically helpfully separating those elements into an array for you so you can work with them.
Well, I need to parse 2 textfiles. 1 named Item.txt and one named Message.txt They are configuration files for a game server, Item contains a line for each item in the game, and Message has Item names, descriptions, server messages etc. I know this is far less than ideal, but I can't change the way this works, or the format.
The idea is in Item.txt I have lines in this format
(item (name 597) (Index 397) (Image "item030") (desc 162) (class general etc) (code 4 9 0 0) (country 0 1 2) (plural 1) (buy 0) (sell 4) )
If I have the php variable $item which is equal to 397 (Index), I need to first get the 'name' (597).
Then I need to open Message.txt and find this line
( itemname 597 "Blue Box")
Then return "Blue Box" to PHP as a variable.
What I'm trying to do is return the item's name with the item's Index.
I know this is probably something really basic, but I've searched though dozens of file operation tutorials and still can't seem to find what I need.
Thanks
Following method doesn't actually 'parse' the files, but it should work for your specific problem...
(Note: not tested)
Given:
$item = 397;
open Item.txt:
$lines = file('Item.txt');
search index $item and get $name:
$name = '';
foreach($lines as $line){ // iterate lines
if(strpos($line, '(Index '.$item.')')!==false){
// Index found
if(preg_match('#\(name ([^\)]+)\)#i', $line, $match)){
// name found
$name = $match[1];
}
break;
}
}
if(empty($name)) die('item not found');
open Message.txt:
$lines = file('Message.txt');
search $name and get $msg:
$msg = '';
foreach($lines as $line){ // iterate lines
if(strpos($line, 'itemname '.$name.' "')!==false){
// name found
if(preg_match('#"([^"]+)"#', $line, $match)){
// msg found
$msg = $match[1];
}
break;
}
}
$msg should now contain Blue Box:
echo $msg;
Not sure if your problem is with parsing the expressions, or reading files per se since you mention "file operation tutorials".
Those parenthetical expressions in your files are called s-expressions. You may want to google for an s-expression parser and adapt it to php.
You should look into the serialize function, which allows data to be stored to a textfile in a format that PHP can reinterpret easily when it needs to be reloaded.
Serializing this data as an array and saving it down to the textfiles would allow you to access it by array keys. Let's take your example. As an array, the data you described would look something like this:
$items[397]['name'] = 'bluebox';
Serializing the item array would put it in a format that could be saved and later accessed.
$data = serialize($items);
//then save data down to the text files using fopen or your favorite class
You could then load the file and unserialize it's contents to end up with the same array. The serialize and unserialize functions are directly intended for this application.
the first text file has several features that you can use to help parse it. It is up to you to decide if it is well formed and reliable enough to key on.
I noticed:
1) a record is delimited by a single line break
2) the record is further delimted by a set of parens ()
3) the record is typed using a word (e.g. item)
4) each field is delimited by parens
5) each field is named and the name is the first 'word'
6) anything after the first word is data, delimited by spaces
7) data with double quotes are string literals, everything else is a number
A method:
read to the end of line char and store that
strip the opening and closing parens
strip all closing )
split at ( and store in temp array (see: http://www.php.net/manual/en/function.explode.php)
element 0 is the type (e.g. item)
for elements 1-n, split at space and store in temp array.
element 0 in this new array will be the key name, the rest is data
once you have all the data compartmentalized, you can then store it in an associative array or database. The exact structure of the array is difficult for me to envision without actually getting into it.
<?php
function aum($x) {
$contents = $_FILES['userfile']['tmp_name'];
$contents = file("$contents");
$aum = $contents[$x][13].$contents[$x][14].$contents[$x][15].$contents[$x][16].$contents[$x][17].$contents[$x][18].$contents[$x][19].$contents[$x][20].$contents[$x][21].$contents[$x][22].$contents[$x][23];
$faum = money_format('%(#1n',$aum)."\n";
return $faum;
}
?>
Notice: A non well formed numeric
value encountered in
./includes.php
on line 28
Hi,
I'm getting the error above. Line 28 is: $faum = money_format('%(#1n',$aum)."\n";
I have three questions:
Why am I getting this error notice and what should I do to fix it?
Is there a better way to upload a CSV text file that has non-uniform comma separation into a HTML table? By "non-uniform" comma separation I mean: KEY DATA,DATA,,,$aum DATA,,,,,,DATA,,etc. As you can see, I am deriving $aum by using the file() function. I then count the number of characters from the right of the beginning of each row to get the fixed character number that corresponds with the $aum DATA. The $x variable corresponds to the row numbers in the file. Then I can return each $aum per row $x. I am new to PHP and would like to know if there is a smarter way to do this.
I appreciate any tips/advice that you might share.
thx,
You need to have a look at $aum as it probably can't be formatted as a number.
Pop
echo $aum;
echo floatval($aum);
Before the error to see what you get. You might need to change the position you're looking at if you're picking up leading or trailing data.
for the second question, fgetcsv is your friend to get data out of CSV files
http://ee.php.net/fgetcsv
For CSV parsing, a hand on approach is to use explode. I try this snippet of code
$string = "a,,b";
$result = explode(",", $string);
echo "<pre>".print_r($result, true)."</pre>";
And the output I get back is:
Array
(
[0] => a
[1] =>
[2] => b
)