Note that there are some explanatory texts on larger screens.

plurals
  1. POUse DOM and XPath to remove a node from a sitemap file
    primarykey
    data
    text
    <p>I am trying to develop a function that removes certain URL nodes from my sitemap file. Here is what I have so far.</p> <pre><code>$xpath = new DOMXpath($DOMfile); $elements = $xpath-&gt;query("/urlset/url/loc[contains(.,'$pageUrl')]"); echo count($elements); foreach($elements as $element){ //this is where I want to delete the URL echo $element; echo "here".$element-&gt;nodeValue; } </code></pre> <p>Which outputs "111111". I don't know why I can't echo a string in a foreach loop if the $elements count is '1'.</p> <p>Up until now, I've been doing</p> <pre><code>$urls = $dom-&gt;getElementsByTagName( "url" ); foreach( $urls as $url ){ $locs = $url-&gt;getElementsByTagName( "loc" ); $loc = $locs-&gt;item(0)-&gt;nodeValue; echo $loc; if($loc == $fullPageUrl){ $removeUrl = $dom-&gt;removeChild($url); } } </code></pre> <p>Which would work fine if my sitemap wasn't so big. It times out right now, so I'm hoping using xpath queries will be faster.</p> <p>After Gordon's comment, I tried:</p> <pre><code>$xpath = new DOMXpath($DOMfile); $query = sprintf('/urlset/url[./loc = "%d"]', $pageUrl); foreach($xpath-&gt;query($query) as $element) { //this is where I want to delete the URL echo $element; echo "here".$element-&gt;nodeValue; } </code></pre> <p>And its not returning anything.</p> <p>I tried going a step further and used codepad, using what was used in the other post mentioned, and did this:</p> <pre><code>&lt;?php error_reporting(-1); $xml = &lt;&lt;&lt; XML &lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;url&gt; &lt;loc&gt;professional_services&lt;/loc&gt; &lt;loc&gt;5professional_services&lt;/loc&gt; &lt;loc&gt;6professional_services&lt;/loc&gt; &lt;/url&gt; XML; $id = '5professional_services'; $dom = new DOMDocument; $dom-&gt;loadXML($xml); $xpath = new DOMXPath($dom); $query = sprintf('/url/[loc = $id]'); foreach($xpath-&gt;query($query) as $record) { $record-&gt;parentNode-&gt;removeChild($record); } echo $dom-&gt;saveXml(); </code></pre> <p>and I'm getting a "Warning: DOMXPath::query(): Invalid expression" at the foreach loop line. Thanks for the other comment on the urlset, I'll be sure to include the double slashes in my code, tried it and it returned nothing.</p>
    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