How to search in an XML file using php?
I don't know if there is a way to search the XML file. For example. I want to get a Value using Name from AttrList and ProductCode . Is it possible? This is how my xml looks like:
<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>
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";
}
Result: Note. Tries to get a property of a non-object . What am I doing wrong?
+3
source to share
2 answers
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
}
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
+6
source to share
You can use DOMXPath for this purpose. Example taken from php.net
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->Load('book.xml');
$xpath = new DOMXPath($doc);
// We starts from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';
$entries = $xpath->query($query);
foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
+2
source to share