0

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

<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 并搜索值?

谢谢。

4

2 回答 2

1

可以在PHP. 首先像往常一样从表中选择整个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
于 2013-05-28T11:33:37.630 回答
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
于 2013-05-28T11:54:35.687 回答