2017-02-23 111 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);。我得到我的完整数据。