2012-02-09 105 views
-1

我迫切需要知道如何阅读下面的XML文件:如何在PHP中从复杂的XML文件中提取各种值?

<uclassify xmlns="http://api.uclassify.com/1/ResponseSchema" version="1.00"> 
<status success="true" statusCode="2000"/> 
    <readCalls> 
    <classify id="cls1"> 
     <classification> 
     <class className="negative" p="0.741735"/> 
     <class className="positive" p="0.258265"/> 
     </classification> 
    </classify> 
    </readCalls> 
</uclassify> 

我需要了解以下内容:

$status_code = ... (should be 2000) 
$negative = ... (the value of p, should be 0.741735) 
$positive = ... (the value of p, should be 0.258265) 

问候

安德烈

+1

你有什么试过的?解析XML有足够的先例,即使在PHP中也是如此。 – deceze 2012-02-09 09:23:05

+1

可能重复的[如何从PHP中的XML文件推断信息](http://stackoverflow.com/questions/1183657/how-to-extrapolate-information-from-xml-file-in-php) – deceze 2012-02-09 09:24:47

+0

['SimpleXML '](http://php.net/manual/en/book.simplexml.php),它的[XPath](http://www.php.net/manual/en/simplexmlelement.xpath.php)引擎可以轻松地做你想做的事。 – DaveRandom 2012-02-09 09:25:10

回答

1
$xml= simplexml_load_file('temp.xml'); 

foreach($xml->status->attributes() as $name => $value){ 
    echo $name.' '.$value.'<br>'; 
    } 
foreach($xml->readCalls->classify->classification->children() as $node){ 
    foreach($node->attributes() as $name => $value) 
    echo $name.' '.$value.'<br>'; 
    } 

o/p:

成功真正 的StatusCode 2000 的className负 p 0.741735 的className积极 p 0.258265

如果你要存储这些:

$status_code = (string)$xml->status->attributes()->statusCode; 
foreach($xml->readCalls->classify->classification->class as $node){ 
    ${(string) $node->attributes()->className} = (string) $node->attributes()->p; 
    } 
echo $status_code.' '.$positive.' '.$negative; 

O/P:

2000 0.258265 0.741735

+0

感谢您的回答! – andrebruton 2012-02-09 15:21:43