Home >php教程 >php手册 >正则表达式 获取xml中的数据解决办法

正则表达式 获取xml中的数据解决办法

WBOY
WBOYOriginal
2016-06-06 19:42:471026browse

正则表达式 获取xml中的数据 Record ItemId="1"Value20110524/Value /Item ItemId="7"Value13.82/Value /Item ItemId="8"Value13.94/Value /Item ItemId="9"Value13.79/Value /Item ItemId="11"Value13.85/Value /Item /Record RecordItemId="1"Value20110525

正则表达式 获取xml中的数据

20110524

13.82

13.94

13.79

13.85


20110525

13.82

13.86

13.58

13.60



这是xml的文件部分内容,就是从里面一个一个的取出value标签后面的值,最好还能得知有几个record。
就是可以应用到自己定义的函数里面,比如
function value($a,$b,$c,$d,$n){
.......
}
for(i=1;i value($a,$b,$c,$d,$i);
}
循环次数:
第一次实现value(13.82,13.94,13.79,13.85,1)
第二次实现value(13.82,13.86,13.58,13.60,2)
------解决思路----------------------
php 提供了专用方法
$s =<<< XML<br />
<Record><br />
<Item Id="1"><Value>20110524</Value><br />
</Item><br />
<Item Id="7"><Value>13.82</Value><br />
</Item><br />
<Item Id="8"><Value>13.94</Value><br />
</Item><br />
<Item Id="9"><Value>13.79</Value><br />
</Item><br />
<Item Id="11"><Value>13.85</Value><br />
</Item><br />
</Record><br />
<Record><Item Id="1"><Value>20110525</Value><br />
</Item><br />
<Item Id="7"><Value>13.82</Value><br />
</Item><br />
<Item Id="8"><Value>13.86</Value><br />
</Item><br />
<Item Id="9"><Value>13.58</Value><br />
</Item><br />
<Item Id="11"><Value>13.60</Value><br />
</Item><br />
</Record><br />
XML;<br />
<br />
$x = simplexml_load_string("<root>$s</root>");<br />
foreach($x->Record as $node) {<br />
  $t = array();<br />
  foreach($node->Item as $v) $t[] = current($v->Value);<br />
  print_r($t);<br />
}<br />
Array<br />
(<br />
    [0] => 20110524<br />
    [1] => 13.82<br />
    [2] => 13.94<br />
    [3] => 13.79<br />
    [4] => 13.85<br />
)<br />
Array<br />
(<br />
    [0] => 20110525<br />
    [1] => 13.82<br />
    [2] => 13.86<br />
    [3] => 13.58<br />
    [4] => 13.60<br />
)<br />
<br />

------解决思路----------------------
<br />
$count=preg_match_all('/<Record>(.+?)<\/Record>/is',$str,$m);<br />
echo $count;<br />
<br />
preg_match_all('/<Value>(.+?)<\/Value>/is',$str,$values);<br />
echo "<pre class="brush:php;toolbar:false">";<br />
print_r($values[1]);<br />
echo "<【本文来自鸿网互联 (http://www.68idc.cn)】/pre>";<br />
/*<br />
2<br />
Array<br />
(<br />
    [0] => 20110524<br />
    [1] => 13.82<br />
    [2] => 13.94<br />
    [3] => 13.79<br />
    [4] => 13.85<br />
    [5] => 20110525<br />
    [6] => 13.82<br />
    [7] => 13.86<br />
    [8] => 13.58<br />
    [9] => 13.60<br />
)<br />
*/<br />
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn