我正在尝试找到一种方法来获取字段和值来读取文件。该文件的构造类似于XML,因此它就像这样..
<tag field1="value1" field2="value2" field3="value3" .... />
<tag2 field5="value5" field6="value6" field7="value7" ... />
..
<tagn .... />
如果我只对一个特定标签感兴趣(例如第一个标签),我怎样才能轻松获取该行的字段和值?
这是我设法做的,但是由于文件是XML构造的,因此可能有一种更简单的方法?
function string2KeyedArray($string, $delimiter = '" ', $kv = '=') {
if ($a = explode($delimiter, $string)) { // create parts separated by a " + space
foreach ($a as $s) { // each part
// Removing the known tag name
$s = str_replace("tag ","",$s);
//removing the starting < and the ending />
$s = str_replace("<","",$s);
$s = str_replace(">","",$s);
$s = str_replace("/","",$s);
//removing the " from the value
$s = str_replace("\"","",$s);
if (strpos($s,"=")) {
if ($pos = strpos($s, $kv)) { // key/value delimiter
$ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
} else { // key delimiter not found
$ka[] = trim($s);
}
}
}
return $ka;
}
}
$string ='<tag field1="value1" field2="value2" field3="value3" />'
$fields = string2KeyedArray($string);
//返回我要找的内容
答案 0 :(得分:1)
我会使用DomDocument。我有一次类似的问题。查看我的代码示例 Here at the bottom of the thread。查看XML文件的链接。 XML FIle。 &#34;的团队站在&#34;将是&#34;标记&#34; &#34;名称&#34;,&#34;胜出&#34;,&#34;损失&#34;将是&#34; field1&#34;,&#34; field2&#34;,&#34; field3&#34;在你的情况下。
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://www.tsn.ca/datafiles/XML/NHL/standings.xml');
$searchNode = $xmlDoc->getElementsByTagName( "team-standing" );
foreach ($searchNode as $searchNode) {
$teamID = $searchNode->getAttribute('id');
$name = $searchNode->getAttribute('name');
$wins = $searchNode->getAttribute('wins');
$losses = $searchNode->getAttribute('losses');
$ot = $searchNode->getAttribute('overtime');
$points = $searchNode->getAttribute('points');
$goalsFor = $searchNode->getAttribute('goalsFor');
$goalsAgainst = $searchNode->getAttribute('goalsAgainst');
$confID = $searchNode->getAttribute('conf-id');
$divID = $searchNode->getAttribute('division-id');
$query = "INSERT INTO standings ('teamid','confid','divid','name','wins','losses','otl','pts','gf','ga')
VALUES ('$teamID','$confID','$divID','$name','$wins','$losses','$ot','$points','$goalsFor','$goalsAgainst')";
$result= $db->query($query);
}
答案 1 :(得分:1)
很抱歉迟到的回复。我想要阅读的文件确实是一个XML文件,我最后使用XML Parser存储在数据库中。 谢谢您的提醒。