2013-03-17 101 views
-2

工作,我有一个txt文件,看起来像这样:读取文件并与内容

<option value="val1">name1</option> 
<option value="val2">name2</option> 
<option value="val3">name3</option> 
<option value="val4">name4</option> 

有该文件中很少的几行,都像她那样。我怎样才能读取该文件,并每行转换为这样的事情 -

$data['val1'] = 'name1'; 
$data['val2'] = 'name2'; 
$data['val3'] = 'name3'; 
$data['val4'] = 'name4'; 

我试过PHP,读文件,装在口袋里添加内容到一个数组中的每一行,那么我卡住了,我不知道如何打破各线成片获得VAL并命名

回答

0

sed是好工具这样的:

sed "s|<option value=\"\(.*\)\">\(.*\)</option>|\$data['\1'] = '\2';|g" test.txt 

\(.*\)段形成两个捕获组,而符合线。然后,我们可以使用\1\2以任何我们想要的方式输出由这些组捕获的文本。

这是唯一有用的,如果你正在寻找一个快速和肮脏的方式来匹配的HTML。如果html比你的例子复杂得多,正则表达式开始崩溃。

+0

[土崩瓦解确实;)](http://stackoverflow.com/questions/1732348/regex-match- open-tags-except-xhtml-self-contained-tags) – Lix 2013-03-17 14:51:05

+0

'sed'做了诡计,谢谢 – 2013-03-17 14:57:08

0

你想要做的是读取每一行和每行,执行strip_tags()函数。这将删除所有HTML元素并仅保留文本数据。在这种情况下,这将是name1/2/3/4/etc ...

一些对你的伪代码 -

$file = fopen("your_file.txt", "r"); // open the file in read-only mode 
$index = 1; // track the line number you are currently on 
$finalArray = array(); // prepare final array to be populated 
while (!feof($file)) { // loop over the entire file, line by line 
    $line = fgets($file); // retrieve the current line of the file 

    // parse string into DOM object 
    $dom = new DOMDocument(); 
    $dom->loadHTML($line); 
    // extract the option tag for this line 
    $tags = $dom->getElementsByTagName('option'); 
    // iterate over the tag list (in our case there will only be one) 
    foreach ($tags as $tag) { 
    // extract the "value" parameter for the key 
    // and perform strip_tags() on the contents 
    $finalArray[$tag->getAttribute('value')] = strip_tags($line); 
    } 
} 
fclose($file); 
+0

'价值'这是不同的每一行,它不是VAL +号 – 2013-03-17 14:35:39

+0

@adr - 我做了一些改变,这应该是你现在正在寻找的东西。 – Lix 2013-03-17 14:44:56

+0

你必须小心格式错误的HTML文件 - 确保你正确处理错误(如果有的话) – Lix 2013-03-17 14:45:44