通過php提取xml的資料問題
我知道php有很多方式從xml中擷取資料,最方便的是通過Regex,但是如果使用DOM方法要怎麼做?
我百度了一下,不是很懂,求大神解釋一下。
比方說
20110524
13.82
13.94
13.79
13.85
20110525
13.82
13.86
13.58
13.60
這一段的xml,我想通過id屬性來擷取對應的值該怎麼辦?
我現在是第一種:
preg_match_all( "/\(.*?)\<\/Value\>/", $Result, $array ); 擷取值之後操作;
第二種:
$doc = new DOMDocument();
$doc->load('sixx.xml'); //讀取xml檔案
$Results = $doc->getElementsByTagName( "Record" );
foreach($Results as $Result){
$Records = $Result->getElementsByTagName("Item");
$times = $Records->item(0)->nodeValue;
}
定位到Item繼續操作
都是沒有利用id的,我想知道如果利用XML的ID取資料改怎麼辦?
我有嘗試用getElementById()擷取,提示沒有這個方法。。。
Call to undefined method DOMElement::getElementById()。
求大神幫忙解答一下,謝謝。
------解決思路----------------------
$s =<<< XML
20110524
13.82
13.94
13.79
13.85
20110525
13.82
13.86
13.58
13.60
XML;
$xml = simplexml_load_string($s);
$t = $xml->xpath('//*[@Id="8"]');
print_r($t);
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Id] => 8
)
[Value] => 13.94
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Id] => 8
)
[Value] => 13.86
)
)
------解決思路----------------------
沒有問題
$xml = simplexml_load_file('6.xml');
foreach( $xml->Item as $a ){
echo $a->Value . '
';
}
20110524
13.82
13.94
13.79
13.85
20110525
13.82
13.86
13.58
13.60
------解決思路----------------------
使用simplexml_load_file 或 simplexml_load_string 就可以把xml轉為數組了。
參考:http://php.net/manual/en/function.simplexml-load-file.php