Note that there are some explanatory texts on larger screens.

plurals
  1. POGet ancestor node with PHP and xpath
    primarykey
    data
    text
    <p>Please forgive if the following is a bit muddled, I've been killing myself trying to work this out.</p> <p>This is a chunk of XML (exported from a much large site) that I am using to create a category tree for a mini-CMS. Once I've got the value and name of the node, which is no problem, I also need to get the 'parent' each node, that is, the node preceding it which is above it in the hierarchy.</p> <pre><code> &lt;productCategory&gt; &lt;genericName&gt;DigitalCinema&lt;/genericName&gt; &lt;productCategories&gt; &lt;productCategory&gt; &lt;genericName&gt;DCinemaProj&lt;/genericName&gt; &lt;productModels&gt; &lt;productModel&gt;ProjProd-1&lt;/productModel&gt; &lt;productModel&gt;ProjProd-2&lt;/productModel&gt; &lt;productModel&gt;ProjProd-3&lt;/productModel&gt; &lt;productModel&gt;ProjProd-4&lt;/productModel&gt; &lt;/productModels&gt; &lt;/productCategory&gt; &lt;productCategory&gt; &lt;genericName&gt;DCinemaLens&lt;/genericName&gt; &lt;/productCategory&gt; &lt;/productCategories&gt; &lt;/productCategory&gt; </code></pre> <p>For example, for the productCategory-genericName <strong>DCinemaLens</strong>, I need to be able to grab the parent as <strong>DigitalCinema</strong>, and similarly for the individual <strong>productModel</strong> nodes, where the parent would be <strong>DCinemaProj</strong>.</p> <p>I've tried various different queries in xpath using ancestor, previous-sibling and parent and I still can't see to grab the node I need.</p> <p>Here is my code as it stands from giving up on my attempts a few minutes ago.</p> <pre><code>if ($xml-&gt;xpath('//productCategories')) { foreach($xml-&gt;xpath('//genericName | //productModel') as $genericName){ echo "&lt;p align='center'&gt;$genericName"; $type = $genericName-&gt;getName(); echo " - (" . $type . ") "; $derp = $xml-&gt;xpath("ancestor::productCategory[1]/genericName"); echo $derp; echo '&lt;/p&gt;'; } } </code></pre> <p>I've also had some success getting information in an array, but it always just returns every value in the XML again.</p> <pre><code>$key = 'genericName'; $derpgleep = $derp[$key]; echo 'Derp= ' . $derpgleep; print_r($derp); </code></pre> <p>Hopefully there is a really easy solution I am overlooking. I hope I have been clear.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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