编程语言
首页 > 编程语言> > PHP-获取XML节点的价值

PHP-获取XML节点的价值

作者:互联网

我有一个像这样的XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<GeteBayDetailsResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2012-07-04T13:54:51.873Z</Timestamp>
  <Ack>Success</Ack>
  <Version>779</Version>
  <Build>E779_CORE_BUNDLED_14986049_R1</Build>
  <SiteDetails>
    <Site>US</Site>
    <SiteID>0</SiteID>
    <DetailVersion>1</DetailVersion>
    <UpdateTime>2009-07-09T10:48:17.000Z</UpdateTime>
  </SiteDetails>
  <SiteDetails>
    <Site>Canada</Site>
    <SiteID>2</SiteID>
    <DetailVersion>1</DetailVersion>
    <UpdateTime>2009-07-09T10:48:17.000Z</UpdateTime>
  </SiteDetails>
</GeteBayDetailsResponse>

我试图找到一种方法来获取SiteID节点等于任何值的SiteID节点的值.

我尝试使用XPath和DomDocument函数,但是没有任何运气.一些混乱的代码如下:

    $xml_file ='SiteDetails.xml';
    $xmlDoc = new DomDocument();
    $xmlDoc->load($xml_file);
    $xpath = new DOMXpath($xmlDoc);

    $xpath->registerNamespace('ebay', 'urn:ebay:apis:eBLBaseComponents');

    //$siteIDList = $xpath->query("/ebay:GeteBayDetailsResponse/ebay:SiteDetails[ebay:Site='UK']/ebay:SiteID");
    //$siteIDList =  $xpath->query("/GeteBayDetailsResponse/SiteDetails[Site=\"UK\"]/SiteID");

//$siteIDList =  $xpath->query("//*[namespace-uri()='urn:ebay:apis:eBLBaseComponents' and name()='Site' and text()='$site']/following-sibling::*[namespace-uri()='urn:ebay:apis:eBLBaseComponents' and name()='SiteID']/text()");

    //var_dump($siteIDList);
    //echo $siteIDList->item(0)->nodeValue;

            /*$SiteDetails = $xmlDoc->getElementsByTagName('SiteDetails');
            $count = 0;
            foreach($SiteDetails as $details){
            //  print_r($details);
            echo $details->nodeValue;
                if ($details->nodeValue == $site){
                    echo 'YEAH';
                    echo $details->SiteID;
                }
            $count ++;  
            }*/
            //$siteID = $siteIDNode->item(8)->nodeValue;        

    //var_dump($siteIDNode);
}

有人可以帮忙吗?从上面可以看出,我很困惑…

解决方法:

通常的想法是,您遍历每个SiteDetails节点,并根据所需的值检查Site节点的值.

假设$xml包含您的xml作为SimpleXML实例

$site = 'Canada';
$siteId = null;

foreach($xml->SiteDetails as $sd) {
  if(((string)$sd->Site) === $site) {
    $siteId = (int)$sd->SiteID;
    //break;
  }
}

var_dump($siteId); //int(2)

Here is a working example on codepad

使用xpath()的解决方案

这是使用xpath()的解决方案

$xml->registerXPathNamespace('ebay','urn:ebay:apis:eBLBaseComponents');
$site = 'Canada';
$siteId = $xml->xpath('ebay:SiteDetails/ebay:Site[text()="'.$site.'"]/../ebay:SiteID');
echo (string)$siteId[0]; //2

working example in codepad

说明:

>首先,通过使用xpath的text()函数返回元素的值,找到带有子节点Site的SiteDetails节点,其子节点Site的值为“ Canada”(或$site中的任何其他值).
>然后,使用.. xpath选择器转到相应的父SiteDetails.
>最后,我们从所需的SiteDetails元素中提取SiteID的值.

祝你好运=)

标签:xpath,domdocument,xml,php
来源: https://codeday.me/bug/20191201/2078320.html