如何使用php在XML文件中搜索? [英] How to search in XML file using php?
本文介绍了如何使用php在XML文件中搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不知道有没有在xml文件中搜索的方法.例如.我想使用 AttrList 和 ProductCode 中的 Name 获取 Value.是否可以 ?这是我的 xml 的样子:
I don't know if there is a method to search in xml file. For instance. I want to get the Value using the Name from AttrList and the ProductCode. Is it possible ? This is how my xml look likes:
<Product>
<ProductCode>70-14UF44-00</ProductCode>
<Vendor>NBM</Vendor>
<ProductType>Soft. Unsorted application</ProductType>
<ProductCategory>Software</ProductCategory>
<ProductDescription>{Bluetooth Driver IVT V.1.4.9.3, 1pk, Full Package, OEM, 1pk for 12M3W/15G3WS, 1pk, 1pk}</ProductDescription>
<Image>https://www.it4profit.com/catalogimg/wic/1/70-14UF44-00</Image>
<ProductCard>https://content.it4profit.com/itshop/itemcard_cs.jsp?ITEM=50409104050320315&THEME=asbis&LANG=ro</ProductCard>
<AttrList>
<element Name="Tipul licentei" Value="Full Package"/>
<element Name="License Conditions" Value="OEM"/>
<element Name="Produs de baza(1)" Value="12M3W/15G3WS"/>
<element Name="Greutatea bruta a pachetului" Value="1.546 kg"/>
<element Name="Bucati in pachet" Value="1"/>
</AttrList>
<MarketingInfo>
<element></element>
</MarketingInfo>
<Images/>
</Product>
我使用 PHP 中的 SimpleXML 库尝试使用 DOMDocument:
Im using the SimpleXML libraries from PHP Trying with DOMDocument:
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->Load('produse_catalog.xml');
$xpath = new DOMXPath($doc);
$query = '//ProductCatalog/Product/ProductCode[. = "PMP5297C_QUAD"]';
$entries = $xpath->query($query);
foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
结果是:注意:试图获取非对象的属性.我做错了什么?
The result is: Notice: Trying to get property of non-object. What am i doing wrong ?
推荐答案
是的,在这种情况下,您可以将 simplexml 与 xpath 结合使用:
Yes you can use simplexml with xpath in this case:
$xml = simplexml_load_file('path/to/xml/file.xml');
$name = 'Tipul licentei';
$product_code = '70-14UF44-00';
$products = $xml->xpath("//Product/ProductCode[contains(text(), '$product_code')]/following-sibling::AttrList/element[@Name='$name']");
if(count($products) > 0) { // if found
$value = (string) $products[0]->attributes()->Value;
echo $value; // Full Package
}
也可以使用 DOMDocument:
Also possible with DOMDocument:
$dom = new DOMDocument();
$dom->load('path/to/xml/file.xml');
$xpath = new DOMXpath($dom);
$name = 'Tipul licentei';
$product_code = '70-14UF44-00';
$value = $xpath->evaluate("string(//Product/ProductCode[contains(text(), '$product_code')]/following-sibling::AttrList/element[@Name='$name']/@Value)");
echo $value; // Full Package
这篇关于如何使用php在XML文件中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文