我有一个像这样的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节点的值,其中Site节点等于任何值。
我尝试过使用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);
}
有人可以帮忙吗?从上面可以看出,我很困惑......
答案 0 :(得分:3)
一般的想法是,您遍历每个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()
$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
说明:
SiteDetails
函数找到具有值为“Canada”(或Site
中的任何其他值)的子节点$site
的{{1}}节点,该函数返回元素的价值。text()
xpath选择器转到相应的父SiteDetails
。..
元素中提取SiteID
的值。祝你好运=)