The code below attempts to find all XML "name" elements that start with 'desk' (using the starts-with method) and trim any leading white space in the XML elements (using the normalize-space and concat methods). However the code isn't retrieving any data. And advice? Thanks in advance!
$xmldoc = simplexml_load_file("products.xml");
$query = $xmldoc->xpath("/products/product[starts-with(normalize-space(concat(' ',name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz')), 'desk')]");
foreach($query as $Products) {
echo $Products->name . " ";
echo $Products->price . "<br>";
}
<products>
<product type="Electronics">
<name> Desktop</name>
<price>499.99</price>
<store>Best Buy</store>
</product>
</products>
I do not believe concat
is the function you want to be using. Your xpath is currently checking if "DesktopABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz" starts with "desk".
Assuming the intent was to lowercase the name element with xpath 1.0, you want to use translate
:
/products/product[
starts-with(
normalize-space(
translate(name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')
),
'desk'
)
]
This lowercases the name element text, removes the leading space and the compares the start with 'desk'.