【问题标题】:PHP Read file content based on pathnamePHP 根据路径名读取文件内容
【发布时间】:2019-08-06 12:01:02
【问题描述】:

更新:

我正在使用RecursiveIteratorIterator 扫描目录以读取index.html 文件。

现在,基于 Pubname 和 Pubversion,我正在尝试读取相应的 index.html 文件,以获取 Readability GradeReadability Score 等的值(通过将值存储在本地存储中)

如果我分别使用html和JS代码,则从本地存储中获取值,但是在我集成到php之后,它就不起作用了。

代码:

<?php
//error_reporting(0);

//Get Pub version
function get_version($path){
    $needle = "=";
    if(($pos = strpos($path, $needle)) != 0){
         $bits = str_split($path, $pos + strlen($needle));

         $integer_count = 0;
         for($x = 0; $x < strlen($bits[1]); $x++){
             if(is_numeric($bits[1][$x])){
                 $integer_count++;
             }else{
                 break;
             }
         }
         if($integer_count > 0){
             $bits = str_split($bits[1], $integer_count);
            return  $bits[0];
         }
    }
    return -1;
}


$it = new RecursiveDirectoryIterator("C:\Users\Sachin_S2\Desktop\Script");

foreach(new RecursiveIteratorIterator($it,RecursiveIteratorIterator::SELF_FIRST) as $file) {

    //IGNORE FILE TYPES
    //$filetypes = array("jpg", "png", "pdf", "css", "csv","log","txt");
    $htmlfiles = array("html");
    $filetype = pathinfo($file, PATHINFO_EXTENSION);
    if (in_array(strtolower($filetype), $htmlfiles)) {

        // skip dot files while iterating
        $it->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);

        $files = array($file);
        $pathname = $file->getPathname();
        print_r($pathname);

        $version = get_version($pathname);
        if($version > 0){
            // use $version to read correct file
            include 'html/home.html';
        }
        echo '*********************************************************************************'.'<br/><br/>';

    }       
}

html/home.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>SEO Metrics</title>
</head>

<body>
        <!--Begin script code-->
        <form name="myform3">
            <!-- 
            <input type="hidden" name="formvar" value="">
            <input type="file" name="file" id="file">
            <p id="demo"></p><br/><br/>
            -->

            <div class="form-group">
              <label>Readability Grade:</label>
              <input type="text" class="form-control" id="grade">
            </div>
            <div class="form-group">
              <label>Readability Score:</label>
              <input type="text" class="form-control" id="score">
            </div>
            <div class="form-group">
              <label>Total Word Count:</label>
              <input type="text" class="form-control" id="words">
            </div>
        </form>
        <!--END script code-->

      <!--Custom JS code-->
      <script src="js/home.js"></script>
</body>
</html>

js/home.js

$(document).ready(function() {


document.getElementById('file').onchange = function() {

    const file = this.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
      const file = event.target.result;
      const allLines = file.split(/\r\n|\n/);
      let arr = allLines;


      arr.forEach((kv) => {
        if (kv.includes("Flesh-Kincaid Grade Level")) { 
                var fetch_grade = kv.replace(/<\/?[^>]+(>|$)/g, "");
                var formated_grade = fetch_grade.split(":").pop();          //Remove part of the string before ":"
                localStorage.setItem("Readability_Grade", formated_grade);

                document.getElementById('grade').value = localStorage.getItem("Readability_Grade").replace(/\s/g, "");  //Assign localStorage to text box
                localStorage["Readability_Grade"] = grade.value;
                //alert(formatedgrade);
        }
        if (kv.includes("Flesh Reading Ease Score")) { 
                var fetch_score = kv.replace(/<\/?[^>]+(>|$)/g, ""); 
                var formated_score = fetch_score.split(":").pop();
                localStorage.setItem('Readability_Score', formated_score);
                document.getElementById('score').value = localStorage.getItem("Readability_Score").replace(/\s/g, "");
                //alert(formatedscore);
        }
        if (kv.includes("Reuse Metrics Score")) { 
                var metricscore = kv; 
                //alert(metricscore);
        }
        if (kv.includes("Total words")) { 
                var totalwords = kv.replace(/<\/?[^>]+(>|$)/g, "");
                var total_words_formated = totalwords.split(":").pop();
                localStorage.setItem('Word_Count', total_words_formated);
                document.getElementById('words').value = localStorage.getItem("Word_Count").replace(/\s/g, ""); 
                //alert(totalwords);
        } 
     }); 
  };

    reader.onerror = (event) => {
      alert(event.target.error.name);
    };

    reader.readAsText(file);
  };

});

输出:

在阅读这个 php 脚本时,我应该能够读取 index html(对于每个文件路径 - 基于 pubname 和版本),并获得我无法获得的 Readability_Grade 和 score 等的值.

【问题讨论】:

  • “我无法根据 pubname 和 pubversion 读取 index.html 文件” - 为什么,实际问题是什么? “我不能”作为问题描述没有帮助。
  • 尝试编辑你的问题,让它更清楚一点,不清楚你在问什么!
  • 我已经编辑了问题@misorude。希望问题现在清楚了吗?请对此提供帮助
  • 不,还不清楚。我不知道您所说的“如何搜索或拆分路径名” 是什么意思。甚至不清楚这里到底应该是什么“输入”和什么“输出”。您是否预先拥有 pubname 和pubversion,现在您想搜索 以查找相应的索引文件?所以基本上你需要做的就是检查当前文件夹名称是否ESXi_6.7_GSG_Pub=9开始
  • 我不知道还需要什么信息。我只需要读取与 Pubname 和 Pubversion 对应的 html 文件。对于 xyz pubname 和 123 pubversion,请阅读 html 文件....对于 abc pubname 和 456 pubversion,请阅读 html 文件。我只需要帮助如何从多个文件路径列表中获取 Pubname 和版本,并在该文件夹中读取其相应的 html 文件。

标签: javascript php html arrays


【解决方案1】:

首先从字符串中获取版本号,下面是一个方法。

function get_version($path){
    $needle = "Pub=";
    if(($pos = strpos($path, $needle)) != 0){
         $bits = str_split($path, $pos + strlen($needle));

         $integer_count = 0;
         for($x = 0; $x < strlen($bits[1]); $x++){
             if(is_numeric($bits[1][$x])){
                 $integer_count++;
             }else{
                 break;
             }
         }
         if($integer_count > 0){
             $bits = str_split($bits[1], $integer_count);
            return  $bits[0];
         }
    }
    return -1;
}

然后你就可以这样使用了。

foreach ($paths as $path){
    $version = get_version($path);
    if($version > 0){
        // use $version to read correct file
    }
}

如果我理解了你的问题。

免责声明:快速输入但应该可以工作。

【讨论】:

  • 我已经根据您的代码@akaBase 修改了代码,现在我需要从 index.html 中获取几个参数(Readability_Grade、Score、..)的值。你能帮忙吗?
  • 那是一个不同的问题,一旦你发布了新问题,我会看看它,如果这回答了你的问题,你能接受吗,
  • 已接受,但问题标题和代码相关,因此在此处更新。我可以用不同的问题发布相同的代码吗? 2个链接不会重复吗!
  • 如果我理解你的话,不应该重复,这个是从路径中获取值,而新的是从 html 中获取值?
  • 我在这里创建了一个新问题:stackoverflow.com/questions/57394548/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2021-10-30
  • 2021-02-23
  • 2021-12-23
  • 1970-01-01
  • 2021-07-21
相关资源
最近更新 更多