2017-02-23 105 views
2

我正在使用PHP編寫的Web服務。我想使用IEEE Explore API顯示數據 - 這是一個REST API。它輸出XML,如下所示。如何使用PHP解析CDATA XML?

我想使用foreach循環解析這些數據。我試圖檢索數據。但問題是所有標籤值都在包裝器內。

我該如何解決這個問題?

<?xml version="1.0" encoding="UTF-8"?> 
<document> 
    <rank>1</rank> 
    <title><![CDATA[Gait Rhythm Fluctuation Analysis for Neurodegenerative Diseases by Empirical Mode Decomposition]]></title> 
    <authors><![CDATA[Peng Ren; Shanjiang Tang; Fang Fang; Lizhu Luo; Lei Xu; Maria L. Bringas-Vega; Dezhong Yao; Keith M. Kendrick; Pedro A. Valdes-Sosa]]></authors> 
    <controlledterms> 
     <term><![CDATA[diseases]]></term> 
     <term><![CDATA[feature extraction]]></term> 
     <term><![CDATA[gait analysis]]></term> 
    </controlledterms> 
    <pubtitle><![CDATA[IEEE Transactions on Biomedical Engineering]]></pubtitle> 
    <punumber><![CDATA[10]]></punumber> 
    <pubtype><![CDATA[Journals &amp; Magazines]]></pubtype> 
    <publisher><![CDATA[IEEE]]></publisher> 
    <abstract><![CDATA[Previous studies have indicated that gait rhythm of gait rhythms.]]></abstract> 
    <issn><![CDATA[0018-9294]]></issn> 
    <arnumber><![CDATA[7422732]]></arnumber> 
    <doi><![CDATA[10.1109/TBME.2016.2536438]]></doi> 
    <publicationId><![CDATA[7422732]]></publicationId> 
    <partnum><![CDATA[7422732]]></partnum> 
</document> 

回答

-1

請檢查代碼:

<?php 
//require_once 'connection.php'; 
function xmlToArray($xml,$ns=null){ 
$a = array(); 
for($xml->rewind(); $xml->valid(); $xml->next()) { 
    $key = $xml->key(); 
    if(!isset($a[$key])) { $a[$key] = array(); $i=0; } 
    else $i = count($a[$key]); 
    $simple = true; 
    foreach($xml->current()->attributes() as $k=>$v) { 
    $a[$key][$i][$k]=(string)$v; 
    $simple = false; 
    } 
    if($ns) foreach($ns as $nid=>$name) { 
    foreach($xml->current()->attributes($name) as $k=>$v) { 
    $a[$key][$i][$nid.':'.$k]=(string)$v; 
    $simple = false; 
    } 
    } 
    if($xml->hasChildren()) { 
    if($simple) $a[$key][$i] = xmlToArray($xml->current(), $ns); 
    else $a[$key][$i]['content'] = xmlToArray($xml->current(), $ns); 
    } else { 
    if($simple) $a[$key][$i] = strval($xml->current()); 
    else $a[$key][$i]['content'] = strval($xml->current()); 
    } 
    $i++; 
} 
return $a; 
} 

$xml = new SimpleXmlIterator('test.xml', null, true); 
$namespaces = $xml->getNamespaces(true); 
// echo '<pre>'; print_r($namespaces); die; 
$arr = xmlToArray($xml,$namespaces); 
echo '<pre>'; print_r($arr); die; 
?> 

我能夠獲得字段的值位於CDATA。將您的XML數據放在test.xml文件中。

+0

是的,它的作品.....謝謝你prakash。 – muraliniceguy97

+0

你的代碼有點複雜,請理解一下。 – muraliniceguy97

-1

我發現另一個簡單的解決方案,當我閱讀php.net文檔時給出瞭解決方案。我只是通過我的網址,像這樣$xml = simplexml_load_file($mainurl, 'SimpleXMLElement',LIBXML_NOCDATA);。我得到我的完整數據。