My code cycles through a CSV file, converting it to XML:
<?php
for ($i = 1; $i < $arraySize; $i++) {
$n = 0;
if (substr($csv[$i][0], 0, 1) == $let) {
$surName = $dom->createElement('name');
$name = $csv[$i][0];
$nameText = $dom->createTextNode($name);
$surName->appendChild($nameText);
$text = str_replace(chr(94), ",", $csv[$i][4]);
$n = $i + 1;
$next = $csv[$n][0];
while ($next == 'NULL') {
$repl = str_replace(chr(94), ",", $csv[$n][4]);
$text = $repl;
$n++;
$next = $csv[$n][0];
}
$bio = $dom->createElement('bio');
$bioText = $dom->createTextNode($text);
$bio->appendChild($bioText);
$person = $dom->createElement('person');
$person->appendChild($surName);
$person->appendChild($bio);
$people->appendChild($person);
}
}
$xmlString = $dom->saveXML();
echo $xmlString;
?>
The problem is the $text = $repl; Typing $text .= $repl; brings:
error on line 1 at column 1: Document is empty.
but omitting the . just gives the last line of text.
the backup code works:
public function test($let){
$csv = $this->readCSV("data\AlphaIndex1M.csv");
$arraySize=sizeof($csv);
$let = strtoupper($let);
//echo '';
for($i=1; $i
echo $csv[$i][0];// .'
echo ', -->'.$csv[$i][4];
$n = $i+1;
$next = $csv[$n][0];
//if($next == 'NULL'){ }
while($next == 'NULL'){
echo $csv[$n][4]. " ";
$n++;
$next=$csv[$n][0];
}
//echo ''
echo '';
}
}
//echo ''
}
You have to initialize your $text before you can append stuff!
So write this before you use it:
$test = "";
(before the while loop or even before the for loop if you want all to be appended)
Related
I'm trying to strip all the dots and then get the number, and NAME[X] as an output.
My output is:
NAME..................................................................................................3
NAME2...................................................................................................24
NAME3...............................................................................................................................................5
NAME4.......................347
NAME5............................................................................................7
NAME6......................................................................9
I've tried something like this so far:
function introExcerpt($id = null, $introExcerptCut = null)
{
$fileInfo['intro'] = 'my string';
$introExcerpt = trim($fileInfo['intro']);
$lines = preg_split('/\r\n|\r|\n/', $introExcerpt);
$intro = '<div class="toc"><ul class="toc">';
for ($i = 0; $i < count($lines); $i++) {
// if (isset($lines[$i]) && substr(trim($lines[$i]), -1) !== '.') {
$intro.= $lines[$i].'<br />';
//}
}
$intro .= '</div></ul>';
return $intro;
}
Not sure exactly what your output should look like, but you may try just running preg_replace directly on the variable containing all lines:
$lines = preg_replace("/(NAME\d+)\.+(\d+)/", "$1[$2]", $lines);
This would generate the following output based on your sample input:
NAME[3]
NAME2[24]
NAME3[5]
NAME4[347]
NAME5[7]
NAME6[9]
You can use the following function:
function introExcerpt($str, $id = null, $introExcerptCut = null)
{
$fileInfo['intro'] = $str;
$introExcerpt = trim($fileInfo['intro']);
$lines = preg_split('/\r\n|\r|\n/', $introExcerpt);
$intro = '<div class="toc"><ul class="toc">';
for ($i = 0; $i < count($lines); $i++) {
$intro .= '<li>';
$tmpLineArray = explode('.', $lines[$i]);
array_filter($tmpLineArray, function ($value) {
return !is_null($value) && $value != '';
});
foreach ($tmpLineArray as $value) {
$intro .= $value . ' ';
}
$intro .= '</li>';
}
$intro .= '</ul></div>';
return $intro;
}
It is splitting the entire row into array using dot as separator and filters out the empty elements.
I'm trying to code Conway look-and-say sequence in PHP.
Here is my code:
function look_and_say ($number) {
$arr = str_split($number . " ");
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
return $res;
}
As I run the function, look_and_say(9900) I am getting value I expected: 2920.
My question is for assigning $arr to be $arr = str_split($number) rather than $arr = str_split($number . " "), the result omits the very last element of the $arr and return 29.
Is it normal to add empty space at the end of the $arr foreach to examine the last element or is there any better way to practice this code - besides regex way.
There are 2 methods I was able to come up with.
1 is to add concatenate at the result after the loop too.
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
$res .= $count . $target;
return $res;
}
And the 2nd one is to add another if clause inside the loop and determine the last iteration:
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
$i=0;
$total = count($arr);
foreach($arr as $num){
if($i == ($total-1))
{
$count++;
$res .= $count . $target;
}
elseif($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
$i++;
}
return $res;
}
I want to suggest you other way using two nested while loops:
<?php
function lookAndSay($number) {
$digits = str_split($number);
$result = '';
$i = 0;
while ($i < count($digits)) {
$lastDigit = $digits[$i];
$count = 0;
while ($i < count($digits) && $lastDigit === $digits[$i]) {
$i++;
$count++;
}
$result .= $count . $lastDigit;
}
return $result;
}
I have to convert a PHP script in Powershell script.
I have current PHP script:
<?php
// read text file
$File = fopen("file.txt", "r") or die("Unable to open file!");
$typePers = array("Personale Viaggiante","Personale Interno");
$excludeFields = array("IT0006","IT0017","IT0077","Personale Viaggiante","Personale Interno","IT0105");
$emptyValue = "NaN";
$rowfinal = "";
// Output one line until end-of-file
while(!feof($File)) {
$row = explode(";",fgets($File));
$substring = "IT0006;IT0017;";
// left string
$lstr = "";
// right string
$rstr = "";
$type = array_intersect($row, $typePers);
$keys = array_keys($type);
if($keys == null) $type = $emptyValue;
else $type = $row[$keys[0]];
$j = 0;
for($i=0; $i<count($row); $i++){
if(in_array($row[$i],$excludeFields)){
unset($row[$i]);
$j++;
}
}
for($i=0; $i<22;$i++)$lstr .= $row[$i].";";
foreach($row as $k => $v)
if($k > 22)if(!empty($v))$rstr .= $v.";";
$rstr = substr($rstr,0,-1);
$substring .= $type;
$substring .= ";IT0077;NaN;IT0105;";
$rowfinal .= $lstr.$substring.$rstr;
}
$file = 'test.txt';
// Write the contents back to the file
file_put_contents($file, $rowfinal);
fclose($sapFile);
?>
I started writing this script in Powershell, but it is incomplete.
$File = Get-Content "file.txt"
$FilePath = "dump.txt"
$typePers = #("Personale Viaggiante","Personale Interno")
$excludeFields = #("IT0006","IT0017","IT0077","Personale Viaggiante","IT0105","Personale Interno")
$emptyValue = "NaN"
$rowfinal = ""
foreach($line in $File) {
[System.Collections.ArrayList]$row = $line -split ";"
$substring = "IT0006;IT0017;"
$lstr = ""
$rstr = ""
$ityp = -1;
for($i=0; $i -lt $row.Count; $i++){
if($typePers -contains $row[$i] ){
$ityp = $i
}
}
if($ityp -eq "-1"){
$type = "NaN"
}else{
$type = $row[$ityp]
}
$j = 0;
for($i=0; $i -lt $row.Count; $i++){
if($excludeFields -contains $row[$i]){
$row.RemoveAt($i)
$j++;
}
}
for($i=0; $i -lt 22;$i++) {
$lstr += $row[$i]+";"
}
$k = 0;
ForEach($v in $row) {
if($k -gt 22) {
if($v -ne ""){
$rstr += $v+";"
}
}
$k++
}
$rstr = $rstr.Substring(0,$rstr.Length-1)
$substring += $type
$substring += ";IT0077;NaN;IT0105;";
$rowfinal += $lstr+$substring+$rstr+"`r`n"
}
$rowfinal | Out-File -FilePath $FilePath
I have only problem with Remove method.
When I have IT0006 value in array, I have IT0105 duplicated...
To end, I have to add header columns for CSV file.
For example, I would to define an array with header:
$header = #('column1','column2',...,'column_n');
and add header at the file to export in CSV.
I'm creating a breadcrumb script like this:
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++)
echo ' » '.$dirlist[$i].'';
?>
If form url is http:// domain /school/students.php,
the result is like this: ( home » school » students.php )
Question: How to eliminate the extension .php file students.php,
be like this ( home » school » students ) ??
No matter how long is the extension or its name, this will work :
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++) {
$result = $dirlist[$i];
if ($i == ($count-1)) { // if last element
$lastDot = strripos($result,'.') ;
$result = substr($result,0,$lastDot) ;
}
echo ' » '.$result.'';
}
?>
how about using string replacement?
Here's a bit of code that may point you in the right direction, replacing your for loop.
for ($i = 0; $i < $count; $i++) {
$label = str_replace('.php', '', $dirlist[$i]);
echo ' » '.$label.'';
}
Try deducting string
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++)
if(!isset($dirlist[$i+1]))
{
echo ' » '.substr($dirlist[$i],0,-4).'';
}
else
{
echo ' » '.$dirlist[$i].'';
}
?>
this will work.
I have been trying to improve this script in PHP so it can give me the value of a to 9999999999.....9999999999 (up to 72 characters) to insert in MySQL. So far it stops at 999. I have increased Apache's memory and the script exuction time but it still stays the same. Here is my script:
<?php
function evol($length = 1, $deb_chaine = '') {
$tab=array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9");
$str = '';
if(strlen($deb_chaine) <= ($length - 1)) {
foreach($tab as $lettre) {
$str .= ' '. $deb_chaine . $lettre;
}
if($deb_chaine == '') {
$str .= evol($length, 'a');
}
else { // sinon
$last = substr($deb_chaine, -1);
$reste = substr($deb_chaine, 0, -1);
if($last == "9") {
$i = strlen($deb_chaine) - 1;
$reste = "";
while($i >= 0) {
if($deb_chaine[$i] == "9") {
$reste = 'a'. $reste;
}
else {
$reste = $tab[(array_search($deb_chaine[$i], $tab) + 1)] . substr($reste, 0, -1);
break 1;
}
$i--;
}
$new = 'a';
}
else {
$new = $tab[(array_search($last, $tab) + 1)];
}
$str .= evol($length, ($reste . $new));
}
}
return $str;
}
echo evol(72);
?>
This code sets the value of a to 999.