从MSSQL中的XML中提取一个值

时间:2013-05-28 11:13:04

标签: php sql sql-server xml

我在MSSQL DB中的一个单元格中包含以下XML:

<receipt reference="INT000003" major="2" minor="14.804" beta="">

<dates id="Booking Dates">    
<item id="Date of Booking">23 May 2013 - 17:09</item>     
</dates>   

<advertisement id="advertisement details">
<item id="Booked by">Mr System Administrator</item>
<item id="Brand or Product">Testing</item>
<item id="Priority">500</item>
</advertisement>

</receipt>

我希望从该单元格中获取值<item id="Brand or Product">Testing</item>(特别是“测试”),以便在基于PHP的网页中使用。有没有人知道任何PHP来读取这种类型的XML并搜索值?

感谢。

2 个答案:

答案 0 :(得分:1)

您可以在PHP中使用DOMXPath::query。首先像往常一样从表中选择整个XML,然后获取正确的元素。

<?php
$xml = <<<END
<receipt reference="INT000003" major="2" minor="14.804" beta="">
  <dates id="Booking Dates">    
    <item id="Date of Booking">23 May 2013 - 17:09</item>     
  </dates>   

  <advertisement id="advertisement details">
    <item id="Booked by">Mr System Administrator</item>
    <item id="Brand or Product">Testing</item>
    <item id="Priority">500</item>
  </advertisement>

</receipt>
END; //you would load it from the table

$dom = new DOMDocument;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$query = "//advertisement/item";

$items = $xpath->query($query);

foreach ($items as $item) {
  echo $item->nodeValue;
}
?>

这将输出

Mr System Administrator
Testing
500

如果您需要特定ID的值,可以使用

<?php
$dom = new DOMDocument;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$query = "//advertisement/item[@id='Brand or Product']";

$items = $xpath->query($query);

foreach ($items as $item) {
  echo $item->nodeValue;
}

输出:

Testing

答案 1 :(得分:1)

这也可以在SQL中完成,如下所示:

declare @xml xml = 
'<receipt reference="INT000003" major="2" minor="14.804" beta="">

<dates id="Booking Dates">    
<item id="Date of Booking">23 May 2013 - 17:09</item>     
</dates>   

<advertisement id="advertisement details">
<item id="Booked by">Mr System Administrator</item>
<item id="Brand or Product">Testing</item>
<item id="Priority">500</item>
</advertisement>

</receipt>'  

select @xml.value
   ('(/receipt/advertisement/item[@id="Brand or Product"])[1]', 'nvarchar(100)')

此外,您可以直接从表中获取值,如下所示:

select cast(YOUR_COLUMN_NAME as XML).value('(/receipt/advertisement/item[@id="Brand or Product"])[1]', 'nvarchar(100)') 
as s from YOUR_TABLE_NAME