我正在尝试使用 php 从 XML 文件中获取特定数据。
我的目标是给函数一个"数字",并得到相应的价格。
价格"603.00",如果我输入数字"swv8814",它将返回"700.00"。
我该怎么做?
<?xml version="1.0" encoding="iso-8859-1" ?>
<Feed>
<Title>CompanyName</Title>
<Email>info@CompanyName.com</Email>
<Products>
<Product>
<Id>4635</Id>
<Number>swv8813</Number>
<Title><![CDATA[&Tradition - Bellevue AJ2 - Floor Lamp White]]></Title>
<Description><![CDATA[]]></Description>
<Category><![CDATA[Lighting]]></Category>
<Stock>0</Stock>
<Price>603.00</Price>
<Discount>0.00</Discount>
<Created>0000-00-00 00:00:00</Created>
</Product>
<Product>
<Id>4635</Id>
<Number>swv8814</Number>
<Title><![CDATA[&Tradition - Bellevue AJ2 - Floor Lamp Black]]></Title>
<Description><![CDATA[]]></Description>
<Category><![CDATA[Lighting]]></Category>
<Stock>0</Stock>
<Price>700.00</Price>
<Discount>0.00</Discount>
<Created>0000-00-00 00:00:00</Created>
</Product>
</Products>
</Feed>
使用这个:
$xmlstr = "<Feed>
<Title>CompanyName</Title>
<Email>info@CompanyName.com</Email>
<Products>
<Product>
<Id>4635</Id>
<Number>swv8813</Number>
<Title><![CDATA[&Tradition - Bellevue AJ2 - Floor Lamp White]]></Title>
<Description><![CDATA[]]></Description>
<Category><![CDATA[Lighting]]></Category>
<Stock>0</Stock>
<Price>603.00</Price>
<Discount>0.00</Discount>
<Created>0000-00-00 00:00:00</Created>
</Product>
<Product>
<Id>4635</Id>
<Number>swv8814</Number>
<Title><![CDATA[&Tradition - Bellevue AJ2 - Floor Lamp Black]]></Title>
<Description><![CDATA[]]></Description>
<Category><![CDATA[Lighting]]></Category>
<Stock>0</Stock>
<Price>700.00</Price>
<Discount>0.00</Discount>
<Created>0000-00-00 00:00:00</Created>
</Product>
</Products>
</Feed>";
$feed = new SimpleXMLElement($xmlstr);
function findPrice($feed, $id){
foreach($feed->Products->Product as $product){
if($product->Number == $id){
return $product->Price;
}
}
return null;
}
echo findPrice($feed, 'swv8813');
echo "'n";
echo findPrice($feed, 'swv8814');
查看它在 3v4l.org 脚本中的工作
使用 DOM 和 Xpath,您可以直接获取值:
$id = 'swv8813';
$xml = file_get_contents('php://stdin');
$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
$expression = sprintf(
'number(/Feed/Products/Product[Number="%s"]/Price)',
str_replace(["'00", '"'], '', $id)
);
var_dump($expression, $xpath->evaluate($expression));
输出:
string(54) "number(/Feed/Products/Product[Number="swv8813"]/Price)"
float(603)
id 值不允许包含零字节或双引号。一个简单的str_replace就可以解决这个问题。
表达...
- 。获取所有
Product
节点.../Feed/Products/Product
- 。按
Number
孩子过滤它们.../Feed/Products/Product[Number="swv8813"]
- 。获取筛选节点的
Price
子节点.../Feed/Products/Product[Number="%s"]/Price
- 。并将找到的第一个
Price
转换为数字。number(/Feed/Products/Product[Number="swv8813"]/Price)