Note that there are some explanatory texts on larger screens.

plurals
  1. POIn DomDocument, reuse of DOMXpath, it is stable?
    primarykey
    data
    text
    <p>I am using the function below, but not sure about it is always stable/secure... <strong>Is it?</strong> </p> <p><strong>When and who is stable/secure to "reuse parts of the DOMXpath preparing procedures"?</strong></p> <p>To simlify the use of the <a href="http://www.php.net/manual/en/domxpath.query.php" rel="nofollow noreferrer">XPath query() method</a> we can adopt a function that memorizes the last calls with static variables,</p> <pre class="lang-php prettyprint-override"><code> function DOMXpath_reuser($file) { static $doc=NULL; static $docName=''; static $xp=NULL; if (!$doc) $doc = new DOMDocument(); if ($file!=$docName) { $doc-&gt;loadHTMLFile($file); $xp = NULL; } if (!$xp) $xp = new DOMXpath($doc); return $xp; // ??RETURNED VALUES ARE ALWAYS STABLE?? } </code></pre> <hr> <p>The present question is similar to <a href="https://stackoverflow.com/q/18086094/287948">this other one</a> about XSLTProcessor reuse. In both questions the problem can be generalized for any language or framework that use LibXML2 as DomDocument implementation. </p> <p>There are another related question: <a href="https://stackoverflow.com/q/20114285/287948">How to &quot;refresh&quot; DOMDocument instances of LibXML2?</a></p> <hr> <h2>Illustrating</h2> <p>The reuse is very commom (examples):</p> <pre><code> $f = "my_XML_file.xml"; $elements = DOMXpath_reuser($f)-&gt;query("//*[@id]"); // use elements to get information $elements = DOMXpath_reuser($f)-&gt;("/html/body/div[1]"); // use elements to get information </code></pre> <p>But, if you do something like <code>removeChild</code>, <code>replaceChild</code>, etc. (example),</p> <pre><code> $div = DOMXpath_reuser($f)-&gt;query("/html/body/div[1]")-&gt;item(0); //STABLE $div-&gt;parentNode-&gt;removeChild($div); // CHANGES DOM $elements = DOMXpath_reuser($f)-&gt;query("//div[@id]"); // INSTABLE! !! </code></pre> <p><strong>extrange things can be occur</strong>, and the queries not works as expected!!</p> <ul> <li><strong>When</strong> (what DOMDocument methods affect XPath?) </li> <li><strong>Why</strong> we can not use something like <a href="http://www.php.net/manual/en/domdocument.normalizedocument.php" rel="nofollow noreferrer">normalizeDocument</a> to "refresh DOM" (exist?)?</li> <li>Only a "new DOMXpath($doc);" is allways secure? need to reload $doc also?</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload