【问题标题】:get data between inverted commas and more获取逗号和更多之间的数据
【发布时间】:2012-09-26 02:08:33
【问题描述】:

我这几天有问题 :s ... 我试图在字符串中获取一些变化的数据,字符串是这样的:

<docdata>
 <!-- News Identifier -->
        <doc-id id-string ="YBY15349" />

        <!-- Date of issue -->
        <date.issue norm ="2012-09-22 19:52" />
        <!-- Date of release -->
        <date.release norm ="2012-09-22 19:52" />
      </docdata>

我需要的只是 "2012-09-22 19:52" 中的 date ,该字符串存储在某种类型的 xml 中,由方式。所以我不能使用普通的 xml 解析器,我已经加载/读取文件来更改一些字符集

    $fname = $file;
    $fhandle = fopen($fname,"r");
    $content = fread($fhandle,filesize($fname));
    str_replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>", $content); 
etc..

这项工作就像一个魅力,但我无法使用字符串。 我尝试使用 preg_match_all 但我无法正确处理。 它有一个简单的方法来搜索这个值

&lt;date.issue norm ="2012-09-22 19:52" /&gt;

只获取变量中的日期?

在此先感谢,对不起我的英语。

【问题讨论】:

  • file_get_contents 对于您的前 3 行更容易。

标签: php xml arrays parsing tags


【解决方案1】:

来自PHP documentation

file_get_contents() 是将文件内容读入字符串的首选方法。如果您的操作系统支持,它将使用内存映射技术来提高性能。

因此,您的代码将变为:

$content = file_get_contents($file);
$content = str_replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>", $content);
preg_match_all('/date\.issue norm ="([^"]+)" /', $content, $date);

默认行为是将带括号的匹配项存储在数组$date[1] 中。因此,您可能会遍历$date[1][0]$date[1][1] 等。

【讨论】:

  • 感谢 Sara,效果很好!!并回答我一些未来的问题。感谢大家抽出宝贵的时间!! :)
  • 没问题! SO提示:您可以通过单击左侧的复选标记来接受您认为最好的答案。
【解决方案2】:

匹配以下内容的正则表达式:

<date.issue norm ="2012-09-22 19:52" />

应该是:

/<date\.issue\s*norm\s*="([^"]*)"/

在代码中:

preg_match_all('/<date\.issue\s*norm\s*="([^"]*)"/', $content, $matches);
// $matches[1] contains all the dates

【讨论】:

    【解决方案3】:

    而不是使用

    fopen($filename)
    

    使用

    $filename = '/path/to/file.xml';
    $filearray = file($filename) // pulls the while file into an array by lines
    
    $searchstr = 'date.issue';
    
    foreach($filearray as $line) {
       if(stristr($line,$searchstr)) { // <-- forgot the )
          $linearray = explode('"',$line);
          // your date should be $linearray[1];
          echo $linearray[1]."\n";  // to test your output
          // rest of your code here
       }
    }
    

    这样你在整个文件中搜索你的搜索字符串,格式错误的 xml 应该不是问题。

    【讨论】:

      猜你喜欢
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多