如何使用php解析此XML

时间:2011-08-22 15:12:51

标签: php xml xpath xml-parsing xbrl

我有以下XML(XBRL)文件

 <xbrli:context id="I2010_ForwardContractsMember">
 <xbrli:entity>
  <xbrli:identifier scheme="http://www.sec.gov/CIK">0000027419</xbrli:identifier>
  <xbrli:segment>
    <xbrldi:explicitMember dimension="us-gaap:DerivativeByNatureAxis">us-gaap:ForwardContractsMember</xbrldi:explicitMember>
  </xbrli:segment>
</xbrli:entity>
<xbrli:period>
  <xbrli:instant>2011-01-29</xbrli:instant>
</xbrli:period>
 </xbrli:context>
<xbrli:context id="D2010Q1">
  <xbrli:entity>
  <xbrli:identifier scheme="http://www.sec.gov/CIK">0000027419</xbrli:identifier>
  </xbrli:entity>
 <xbrli:period>
    <xbrli:startDate>2010-01-31</xbrli:startDate>
    <xbrli:endDate>2010-05-01</xbrli:endDate>
  </xbrli:period>
 </xbrli:context>

我想在id =“D2010Q1”时获取startDate和endDate值

我的代码正在关注

 $xml = new SimpleXMLElement($sec_file);
 $xml -> registerXPathNamespace('us-gaap', "http://fasb.org/us-gaap/2011-01-31");

  foreach ($xml->xpath('//xbrli:context') as $item) {

if ($item -> attributes() -> id == 'D2010Q1') {
    //print_r($item -> xpath('//xbrli:startDate'));
    echo $item->xpath('//xbrli:startDate');
    echo '<br>';
    break;
}
}

我不知道如何获取startDate和endDate值。 有什么建议吗?

原始xml位于

http://www.sec.gov/Archives/edgar/data/27419/000110465911031717/tgt-20110430.xml

2 个答案:

答案 0 :(得分:1)

您还需要注册xbrli命名空间,类似于您使用us-gaap所做的操作。 从WikiPedia我发现了这一点 的xmlns:xbrli = “http://www.xbrl.org/2003/instance”

答案 1 :(得分:1)

修改

  

我是否需要在文件中注册所有命名空间?我怎么能得到startDate和endDate infor?

不,您只需注册所需的名称空间即http://www.xbrl.org/2003/instance

$xmldoc = new DOMDocument();
$xmldoc->load("http://www.sec.gov/Archives/edgar/data/27419/000110465911031717/tgt-20110430.xml");
$xpath = new DOMXPath($xmldoc);
$xpath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$nodelist = $xpath->query("/xbrli:xbrl/xbrli:context[@id='D2010Q1']/xbrli:period"); // much faster than //xbrli:context and //xbrli:startDate
if($nodelist->length === 1)
{
    $period = $nodelist->item(0);
    $nodelist = $xpath->query("xbrli:startDate", $period);
    $startDate = $nodelist->length === 1 ? $nodelist->item(0)->nodeValue : null;
    $nodelist = $xpath->query("xbrli:endDate", $period);
    $endDate = $nodelist->length === 1 ? $nodelist->item(0)->nodeValue : null;
    printf("%s<br>%s", $startDate, $endDate);
}
else
    ; // not found or more than one <xbrli:context id='D2010Q1'><xbrli:period>

旧:

$xmldoc = new DOMDocument();
$xmldoc->load("http://www.sec.gov/Archives/edgar/data/27419/000110465911031717/tgt-20110430.xml");
$xpath = new DOMXPath($xmldoc);
$xpath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$nodelist = $xpath->query("/xbrli:xbrl/xbrli:context[@id='D2010Q1']/xbrli:period/xbrli:startDate"); // much faster than //xbrli:context and //xbrli:startDate
if($nodelist->length === 1)
    print $nodelist->item(0)->nodeValue;
else
    ; // not found or more than one <xbrli:context id='D2010Q1'><xbrli:period>