2016-04-30 57 views
0

我有一个看起来像这样的XML文件,我想解析为常规XML,尝试循环值,尤其是Cell值。在PHP中解析XML名称空间格式

<APIReport xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Rochester.Models"> 
<Column xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
    <d2p1:string>Name</d2p1:string> 
    <d2p1:string>Surname</d2p1:string> 
</Column> 
<Dates>29-04-2016, 00:00:00 - 29-04-2016, 23:59:59</Dates> 
<Id>1200</Id> 
<Row> 
    <APIReportRow> 
     <Cell xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
      <d4p1:string>Francesco</d4p1:string> 
      <d4p1:string>Delolli</d4p1:string> 
     </Cell> 
    </APIReportRow> 
    <APIReportRow> 
     <Cell xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
      <d4p1:string>Roberto</d4p1:string> 
      <d4p1:string>Delolli</d4p1:string> 
     </Cell> 
    </APIReportRow> 
</Row> 
<Title>Nomi</Title> 

所以我试图解析它在PHP中使用SimpleXML,使用这种简单的代码:

$xml = simplexml_load_string($xmlstring); 
print_r($xml); 

Cell值为空:

SimpleXMLElement Object 
(
    [Column] => SimpleXMLElement Object 
     (
     ) 

    [Dates] => 29-04-2016, 00:00:00 - 29-04-2016, 23:59:59 
    [Id] => 1200 
    [Row] => SimpleXMLElement Object 
     (
      [APIReportRow] => Array 
       (
        [0] => SimpleXMLElement Object 
         (
          [Cell] => SimpleXMLElement Object 
           (
           ) 

         ) 

        [1] => SimpleXMLElement Object 
         (
          [Cell] => SimpleXMLElement Object 
           (
           ) 

         ) 

       ) 

     ) 

    [Title] => Nomi 
) 

我的问题很简单:我如何获得XML的Cell值?

+1

您是否尝试过直接访问到一些小区基站的价值?像这样:echo(string)$ xml-> Row-> APIReportRow [0] - > Cell; – nanocv

+1

单元格值不为空,'print_r'不能处理SimpleXML的精彩:P访问'Cell'内部元素的关键是他们使用“namespaces”(标签中带有':')。为此,你需要['children()'方法](http://php.net/manual/en/simplexmlelement.children.php)。 – IMSoP

回答

0

感谢@IMSoP,我得到了解决:

$xml = simplexml_load_string($xmlstring); 
$rows = $xml->Row->APIReportRow; 
foreach ($rows as $row) { 
    $cell = $row->Cell->children('d4p1', true); 
    echo "Name: " . (string) $cell->string[0] . "\n"; 
    echo "Surname: " . (string) $cell->string[1] . "\n"; 
}