How can i import information from a file (like below) to my mysql database by a php file?
I was thinking by open a file, insert a row into a variabele and check every line for an = mark and insert the information into array's by checking the tag bevore the =.
Is this the right way or are there better ways.
Example file:
# Disc length: 926 seconds
# Revision: 0
# Processed by: cddbd v1.5PL3 Copyright (c) Steve Scherf et al.
# Submitted via: audiograbber 1.83.01
DISCID=00039c14
DTITLE=3M Littmann Stethoscope Edition / 20 Beispiele zur Herz- und Lungenausku
DTITLE=ltation
DYEAR=1997
DGENRE=Medizin
TTITLE0=Normale Herztöne
TTITLE1=Dritter Herzton (physiologisch)
TTITLE2=Vierter Herzton
TTITLE3=Aortenklappenstenose
TTITLE4=Mitralklappeninsuffizienz
TTITLE5=Mittelsystolischer Klick
TTITLE6=Ventrikelseptum-Defekt
TTITLE7=Atriumseptum-Defekt
TTITLE8=Mitralklappenstenose
TTITLE9=Aortenklappeninsuffizienz
TTITLE10=normales tracheales Atemgeräusch
TTITLE11=normales vesikuläres Atemgeräusch
TTITLE12=feine Krepitation mit leichter bronchialer Atmung
TTITLE13=rauhe Krepitation
TTITLE14=bronchiale Atmung
TTITLE15=Stridor beim Einatmen
TTITLE16=Rhonchus
TTITLE17=pfeifender Rhonchus (Keuchatmen)
TTITLE18=feine Krepitation (Knisterrasseln)
TTITLE19=pleurales Reibungsgeräusch
EXTD=
EXTT0=
EXTT1=
EXTT2=
EXTT3=
EXTT4=
EXTT5=
EXTT6=
EXTT7=
EXTT8=
EXTT9=
EXTT10=
EXTT11=
EXTT12=
EXTT13=
EXTT14=
EXTT15=
EXTT16=
EXTT17=
EXTT18=
EXTT19=
PLAYORDER=
Try this:
$settingArray = array();
$text = file('file.txt');
foreach($text as $line){
$line = str_replace(array("\r", "\n"), '', $line);
if(substr($line, 0, 1) != '#' && !empty($line)){
$key = substr($line, 0, strpos($line, "="));
$value = substr($line, strpos($line, "=") + 1);
$value = substr($value, 0, strpos($value, "#") != 0 ? strpos($value, "#") : strlen($value)); //removes everything behind a # sign
$settingArray[$key] = $value;
}
}
var_dump($settingArray);
/*this will print:
array (size=46)
'DISCID' => string '00039c14' (length=8)
'DTITLE' => string 'ltation' (length=7)
'DYEAR' => string '1997' (length=4)
'DGENRE' => string 'Medizin' (length=7)
'TTITLE0' => string 'Normale Herztöne ' (length=17)
'TTITLE1' => string 'Dritter Herzton (physiologisch)' (length=31)
'TTITLE2' => string 'Vierter Herzton' (length=15)
'TTITLE3' => string 'Aortenklappenstenose' (length=20)
'TTITLE4' => string 'Mitralklappeninsuffizienz' (length=25)
'TTITLE5' => string 'Mittelsystolischer Klick' (length=24)
'TTITLE6' => string 'Ventrikelseptum-Defekt' (length=22)
'TTITLE7' => string 'Atriumseptum-Defekt' (length=19)
'TTITLE8' => string 'Mitralklappenstenose' (length=20)
'TTITLE9' => string 'Aortenklappeninsuffizienz' (length=25)
'TTITLE10' => string 'normales tracheales Atemgeräusch' (length=32)
'TTITLE11' => string 'normales vesikuläres Atemgeräusch' (length=33)
'TTITLE12' => string 'feine Krepitation mit leichter bronchialer Atmung' (length=49)
'TTITLE13' => string 'rauhe Krepitation' (length=17)
'TTITLE14' => string 'bronchiale Atmung' (length=17)
'TTITLE15' => string 'Stridor beim Einatmen' (length=21)
'TTITLE16' => string 'Rhonchus' (length=8)
'TTITLE17' => string 'pfeifender Rhonchus (Keuchatmen)' (length=32)
'TTITLE18' => string 'feine Krepitation (Knisterrasseln)' (length=34)
'TTITLE19' => string 'pleurales Reibungsgeräusch' (length=26)
'EXTD' => boolean false
'EXTT0' => boolean false
'EXTT1' => boolean false
'EXTT2' => boolean false
'EXTT3' => boolean false
'EXTT4' => boolean false
'EXTT5' => boolean false
'EXTT6' => boolean false
'EXTT7' => boolean false
'EXTT8' => boolean false
'EXTT9' => boolean false
'EXTT10' => boolean false
'EXTT11' => boolean false
'EXTT12' => boolean false
'EXTT13' => boolean false
'EXTT14' => boolean false
'EXTT15' => boolean false
'EXTT16' => boolean false
'EXTT17' => boolean false
'EXTT18' => boolean false
'EXTT19' => boolean false
'PLAYORDER' => boolean false*/
You should simple ignore lines starting with # and then in all other lines (not-empty) find first occurrence of = sign and using susbtr (or mb_substr) you will get columns and columns values.
EDIT
Someone suggest it's INI file however in fact it isn't so you cannot use parse_ini_file function. First thing is that comments here start with '#` what would generate Deprecated warning (ini PHP 5.5.12) and in addition because no quotes were used you will get warning :
Warning: syntax error, unexpected '(' in test.ini on line 12
and this function will return false
EDIT2
I would do it this way:
<?php
$data = array();
$lines = file('test.ini');
mb_internal_encoding('UTF-8');
foreach($lines as $line){
$line = trim($line);
if ($line == '' || mb_substr($line,0,1) == '#') {
continue;
}
$pos = mb_strpos($line, '=');
if ($pos == false) { // == not ===
continue;
}
$data[mb_substr($line,0,$pos)] = mb_substr($line, $pos + 1);
}
var_dump($data);
You need to trim each line first and remove empty lines and lines starting with # as I said before, then you check for occurrence of =. If it's not found or at 0 position simple you need to ignore this line, all other lines are placed into $data array
Related
the problem s in the 'decimal_point' => string '/'
but did anyone have a good solution to fix it?
the error:
preg_match() unknown modifier '?'
the function :
* #param string $str input string
* #return boolean
*/
public static function numeric($str)
{
// Get the decimal point for the current locale
list($decimal) = array_values(localeconv());
// A lookahead is used to make sure the string contains at least one digit (before or after the decimal point)
return (bool) preg_match('/^-?+(?=.*[0-9])[09]*+'.preg_quote($decimal).'?+[0-9]*+$/D', (string) $str);
}
it's localeconv() dump :
array (size=18)
'decimal_point' => string '/' (length=1)
'thousands_sep' => string ',' (length=1)
'int_curr_symbol' => string 'IRR' (length=3)
'currency_symbol' => string 'ريال' (length=8)
'mon_decimal_point' => string '/' (length=1)
'mon_thousands_sep' => string ',' (length=1)
'positive_sign' => string '' (length=0)
'negative_sign' => string '-' (length=1)
'int_frac_digits' => int 2
'frac_digits' => int 2
'p_cs_precedes' => int 0
'p_sep_by_space' => int 0
'n_cs_precedes' => int 0
'n_sep_by_space' => int 0
'p_sign_posn' => int 3
'n_sign_posn' => int 3
'grouping' =>
array (size=1)
0 => int 3
'mon_grouping' =>
array (size=1)
0 => int 3
the relate issue on github
koseven/issues #351
Since you're using / as the delimiter in your regexp, pass it to the preg_quote function as well, as the second parameter:
return (bool) preg_match('/^-?+(?=.*[0-9])[09]*+' . preg_quote($decimal, '/') . '?+[0-9]*+$/D', (string) $str);
// -----------------------------------------------------------------------^
Quote from the manual:
Note that / is not a special regular expression character.
[...]
delimiter
If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required
by the PCRE functions. The / is the most commonly used delimiter.
I am using PHP Version 5.6.25. The following code is all that's needed to replicate the issue.
$data['foo'] = true;
$data['bar'] = false;
var_dump($data);
$data['foo'] = nl2br($data['foo']);
$data['bar'] = nl2br($data['bar']);
array_walk_recursive($data, "filter");
var_dump($data);
This gives the following result.
array (size=2)
'foo' => boolean true
'bar' => boolean false
array (size=2)
'foo' => string '1' (length=1)
'bar' => string '' (length=0)
Is this a PHP bug? Is there a workaround?
from the manual nl2br
string nl2br ( string $string [, bool $is_xhtml = true ] )
nl2br expects a string as an input, casting a boolean to a string returns 1 for true and "" for false; so no surprises that's what you get in this case.
In your filter function you can check the variable type before deciding how to filter it.
I have an php array like this (var_dump)
I need change one of it's element
array (size=204)
'Address' =>
array (size=3)
'City' =>
array (size=3)
0 => string 'return $this->hasOne(City::className(), ['id' => 'cityId']);'
1 => string 'City' (length=4)
2 => boolean false
'CityDistrict' =>
array (size=3)
0 => string 'return $this->hasOne(CityDistrict::className(), ['id' => 'cityDistrictId']);' (length=76)
1 => string 'CityDistrict' (length=12)
2 => boolean false
'Contacts' =>
array (size=3)
0 => string 'return $this->hasMany(Contact::className(), ['addressId' => 'id']);'
1 => string 'Contact' (length=7)
2 => boolean true
'City' =>
array (size=3)
'Addresses' =>
array (size=3)
0 => string 'return $this->hasMany(Address::className(), ['cityId' => 'id']);'
1 => string 'Address' (length=7)
2 => boolean true
'Region' =>
array (size=3)
0 => string 'return $this->hasOne(Region::className(), ['id' => 'regionId']);' (length=64)
1 => string 'Region' (length=6)
2 => boolean false
'CityDistricts' =>
array (size=3)
0 => string 'return $this->hasMany(CityDistrict::className(), ['cityId' => 'id']);'
1 => string 'CityDistrict' (length=12)
2 => boolean true
'CityDistrict' =>
array (size=2)
Addresses =>
array (size=3)
0 => string 'return $this->hasMany(Address::className(), ['cityDistrictId' => 'id']);'
1 => string 'Address' (length=7)
2 => boolean true
'City' =>
array (size=3)
0 => string 'return $this->hasOne(City::className(), ['id' => 'cityId']);'
1 => string 'City' (length=4)
2 => boolean false
How can i change value 'CityDistrict' in this loop? or 'Addresses'? using php foreach
My code doesn't work please help understand what wrong!
private static function checkExistClass($relations)
{
foreach ($relations as $name => $relation) {
foreach ($relation as $functionName => $functionValue) {
$functionNameGet = 'get' . $functionName;
$directory = new Model;
if (method_exists($directory, $functionNameGet)) {
$relation['funky_key_' . $functionName] = $functionValue;
unset($relation[$functionName]);
}
}
}
return $relations;
}
I interprete your question that you want to rename the array index Addresses to NewAddresses:
$relations['CityDistrict']['NewAddresses'] = $relations['CityDistrict']['Addresses'];
unset($relations['CityDistrict']['Addresses']);
EDIT:
to do that in your foreach loop, change:
$relation['funky_key_' . $functionName] = $functionValue;
unset($relation[$functionName]);
to:
$relations[$name]['funky_key_'.$functionName] = $functionValue;
unset($relations[$name][$functionName]);
maybe this is what you're looking
if (isset($array['n'])) {
$array['name'] = $array['n'];
unset($array['n']);
}
you can see the complete post in Change key in associative array in PHP
see you!
PD Sorry, for my english is not the best
Your loop seems wrong. In the outer loop, $name assumes values such as 'Address', and $relation is an array such as { 'City' => ..., 'CityDistrict' => ... }.
So in the second loop $functionName assumes values such as City, CityDistrict and Contacts.
If you want to change that, you need to do something like #hellcode suggested:
if ('CityDistrict' == $functionName) {
$relations[$name]['NewDistrict'] = $relations[$name][$functionName];
unset($relations[$name][$functionName]);
continue;
}
This looks like a Laravel/Eloquent problem to me. If you can state more precisely what it is that you're trying to accomplish, possibly someone could be of more use.
Also, you seem to want to create a function given its code in a string. To do this you would need create_function (or declare the function as anonymous/lambda function):
$code = "return 42;";
$array['function'] = create_function('', $code);
print $array['function']();
Note that the use of create_function is somewhat deprecated. Also you need a PHP > 5.3+ (or 5.4+ if you go lambda and require $this).
im sitting with a pretty simple image uploader, where the first image uploaded is going to be treated in a special manner. I then run a loop over all the files, and skip the first image.
For this i have named the first image headImage, and i skip it when it has been moved, and done the other stuff to it.
I have cut out all excess code, and are only displaying the loop causing my problem:
Sorted image array:
array (size=5)
'headImage' =>
array (size=5)
'name' => string '8-skilling-1606-eller-07-54-1-h93a.jpg' (length=38)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string '/tmp/phpNUoAtX' (length=14)
'error' => int 0
'size' => int 37748
0 =>
array (size=5)
'name' => string '807003718_2_Big.jpg' (length=19)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string '/tmp/php1TXBdm' (length=14)
'error' => int 0
'size' => int 36328
Foreach loop which skips if the fileKey is "headImage", and dumps the fileKey
foreach($uploadFiles as $fileKey => $file){
if($fileKey == "headImage"){
var_dump($fileKey);
continue;
}
}
And the output from var_dump:
string 'headImage' (length=9)
int 0
Now, why is the if sentence ran when the value of $fileKey clearly isn't "headImage"?
Because "string" == 0 in PHP.
You have to compare using type too, try === comparison:
foreach($uploadFiles as $fileKey => $file){
if($fileKey === "headImage"){
var_dump($fileKey);
continue;
}
}
best and safe way to compare two string is using php strcmp function
use like this :
foreach($uploadFiles as $fileKey => $file){
if(strcmp($fileKey ,"headImage") == 0){
var_dump($fileKey);
continue;
}
}
PHP strcmp function Document
I need to parse a lot of files and get their header declaration from all of them and add them all to an array..It doesnt matter if its the same or not since i'll use array_unique after to get only the unique once.
Some files have comments on the top so i can just pick the first line. The declaration is like this:
private ["_aaaaaaa", "_bbbbbb", "_ccccc", "_dddddddd"];
but sometimes it can be like this (no space)
private["_aaaaaaa","_bbbbbb","_ccccc","_dddddddd"];
or like this (if the guy who wrote it didnt pay attention)
private["_aaaaaaa", "_bbbbbb","_ccccc", "_dddddddd"];
So far i got this:
<?php
$str = 'private ["_aaaaaaa","_bbbbbb","_ccccc","_dddddddd"];';
$arr = Array();
$start = 'private [';
$end = '];';
$pattern = sprintf(
'/%s(.+?)%s/ims',
preg_quote($start, '/'), preg_quote($end, '/')
);
if (preg_match($pattern, $str, $matches)) {
list(, $match) = $matches;
echo $match;
}
?>
which outputs :
"_aaaaaaa","_bbbbbb","_ccccc","_dddddddd"
Still though that doesnt cover it....plus how will i make that to an array...?
Is there a simple way of doing this ? I've got the function that parses all the files in a folder and subfolder...i just need first to parse all the files and make this array which i'll later use in my main function.
Any help would be appreciated.
-Thanks
This should work -
/*
Function-> get_header()
Input -> The header string.
Output -> An array of header's parameters.
*/
function get_header($string){
if(preg_match("/private\s?\[(.*?)\];/", $string, $matches)){
return preg_split("/(\s*)?,(\s*)?/",$matches[1]);
}
return Array();
}
//Assuming these to be the different file headers.
$headers = Array(
'private ["_aaaaaaa", "_bbbbbb", "_ccccc","_dddddddd"];',
'private ["_4","_3","_2","_1" ];',
'private["_a", "_b","_c", "_d"];'
);
$header_arr = Array();
foreach($headers as $h){
$header_arr = array_merge($header_arr, get_header($h));
}
var_dump($header_arr);
OUTPUT-
/*
array
0 => string '"_aaaaaaa"' (length=10)
1 => string '"_bbbbbb"' (length=9)
2 => string '"_ccccc"' (length=8)
3 => string '"_dddddddd"' (length=11)
4 => string '"_4"' (length=4)
5 => string '"_3"' (length=4)
6 => string '"_2"' (length=4)
7 => string '"_1" ' (length=5)
8 => string '"_a"' (length=4)
9 => string '"_b"' (length=4)
10 => string '"_c"' (length=4)
11 => string '"_d"' (length=4)
*/