2

This is my xml.

    <episodes>
        <episode>
           <series_name>Test</series_name>
            <season_number>1</season_number>
            <episode_number>10</episode_number>
            <episodes_in_season>12</episodes_in_season>
            <notes>Testing</notes>
         </episode>
    </episodes>

What i want to do is get the number of season/episode number and increment or decrement i from that xml and then save it back (i have +/- buttons on my page for season_number and for episode_number, and i am using `$_post for that button).

And here is my code so far.

$xmlDoc = new DOMDocument();
$xmlDoc->load($user);
$xpath = new DOMXpath($xmlDoc);
$test = $xmlDoc->getElementsByTagName('episode')->item(0);

// example for episode number increment / decrement (what i think)

   $number = $test->childNodes->item(2); 

    $increment = $number + 1; 
    $decrement = $number - 1; // example 

i am stuck here and i didn't complete it since i can't see whats going on in $number because i am getting this error Object of class DOMElement could not be converted to int.

i have also tried it with (int)$number = $test->childNodes->item(2); but with no luck. And also i am a beginner in php so i might got this thing wrong all together.

edit:

  $eNumber = $xpath->query('episode_number', 'episode')->item(0);
      $esNumber = $xpath->query('episodes_in_season', 'episode')->item(0);
     if ($eNumber == $esNumber)
     {
        echo "You have reached the max episode in season";

     }
     else
     {

     $eNumber->nodeValue++;
     }

it always says i have reached the max episode

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
MePo
  • 1,044
  • 2
  • 23
  • 48

2 Answers2

2

The DOMNodelist::item() method you are using does not return a value (neither string nor integer), it returns a node:

DOMNode DOMNodelist::item ( int $index )

As such (and assuming your Xpath query was correct), you need to access its nodeValue property to read the number. Then, if you cast to integer make sure you do it before you assign the result to a variable:

$number = (int)$test->childNodes->item(2)->nodeValue; 

... though it's normally not necessary since PHP will do it for you as soon as you do math:

$foo = '33';
var_dump($foo); // string(2) "33"
$foo++;
var_dump($foo); // int(34)
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
2

If $number is the DOMElement corresponding to episode_number, do the following to increment:

$number->nodeValue++;

By the way, instead of $number = $test->childNodes->item(2); I would recommend XPath to always address the correct element:

$number = $xpath->query('episode_number', $test)->item(0);
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111