PHP SimpleXML XPath gets the next parent node

I never asked questions here, so please forgive my question if it is poorly formatted or not well defined. I am just a dabbler and know very little about PHP and XPath.

I have an XML file:

<catalogue>
 <item>
  <reference>A1</reference>
  <title>My title1</title>
 </item>
 <item>
  <reference>A2</reference>
  <title>My title2</title>
 </item>
</catalogue>

I pulled this file using SimpleXML:

$file = "products.xml";
$xml = simplexml_load_file($file) or die ("Unable to load XML file!");

Then I use the link from the URL parameter to get additional information about the "element" using PHP:

foreach ($xml->item as $item) {
if ($item->reference == $_GET['reference']) {
 echo '<p>' . $item->title . '</p>';
}

So, from a URL like www.mysite.com/file.php?reference=A1

I would get this HTML:

<p>My title1</p>

I understand that I may not be doing it right, and any recommendations for improving it are welcome.

: . URL-, reference = A1, , .. ""? "A1", , node, HTML :

<p>Next item is My title2</p>

, , . node, , .

.

+3
2

:

/catalogue/item[reference='A1']/following-sibling::item[1]/title

: item catalogue, reference "A1", sibling item title.

+3

, xpath / ( ) node.

<?php

error_reporting(E_ALL ^ E_NOTICE);

$s = '
<catalogue>
 <item>
  <reference>A1</reference>
  <title>My title1</title>
 </item>
 <item>
  <reference>A2</reference>
  <title>My title2</title>
 </item>
 <item>
  <reference>A3</reference>
  <title>My title3</title>
 </item>
</catalogue>
';

$xml = simplexml_load_string($s);
$reference = 'A3';

list($current) = $xml->xpath('/catalogue/item[reference="' . $reference . '"]');

if($current) {
    print 'current: ' . $current->title . '<br />';

    list($prev) = $current->xpath('preceding-sibling::*[1]');

    if($prev) {
        print 'prev: ' . $prev->title . '<br />';   
    }

    list($next) = $current->xpath('following-sibling::*[1]');

    if($next) {
        print 'next: ' . $next->title . '<br />';   
    }
}

. SimpleXMLElement::xpath XPath.

+2

Source: https://habr.com/ru/post/1762841/


All Articles