Sander Dult Sander Dult - 1 year ago 62
PHP Question

attributes in root cause xml file to not load by simplexml php

So, this is a follow-up question to my previous question that was solved, here's the link to it:
using data from child element to select data in other element using simplexml in php

thanks to @RomanPerekhrest for solving this.

I have this piece of php code using simplexml to read my xml file


$xml = simplexml_load_file('../uploads/reports/report.xml');

$hits = $xml->xpath("results/hits/@rule_id");
$ruleIds = array_map(function($v){ // getting search path for each needed rule
return "profile_info/rules/rule[@id='". (string)$v. "']";
}, $hits);

foreach ($xml->xpath(implode(" | ", $ruleIds)) as $rule) {
echo '<div id="name">'. $rule->display_name .'</div>'.
'<div id="comment">'. $rule->display_comment .'</div>';

again, thanks to @RomanPerekhrest for coming up with this.

This piece of code works fine with my simplified xml-file I created to illustrate my problems in my previous questions, but when I apply it, it doesn't seem to render.

I've found the reason why, in my root element there are some xmlns attributes that cause my xml not to load. When I manually remove these attributes, everything works as expected. (I will not the list the entire xml document, since it is 8500+ lines long)
Here is the root element with the attributes:

<report xsi:schemaLocation=" pi4_results_schema.xsd" xmlns="" xmlns:xsi="">

I need a way to bypass in php. Seeing as these xml files are generated by other software and the lack of settings in this generation, I cannot simply make these xml files without these attributes.


Answer Source

Your XML has default namespace declared at the root element, which descendant elements without prefix inherit implicitly :


To reference element in default namespace, you need to map a prefix to the default namespace URI, and then use that prefix in your XPath :

//register prefix 'd' to reference default namespace URI
$xml->registerXPathNamespace('d', '');

//use the prefix to reference elements in the default namespace
$hits = $xml->xpath("d:results/d:hits/@rule_id");
$ruleIds = array_map(function($v){    // getting search path for each needed rule
    return "d:profile_info/d:rules/d:rule[@id='". (string)$v. "']"; 
}, $hits);