Mokus
Mokus

Reputation: 10400

Get tag content

I have the following xml structure

<description>
    <category id="HBLMENEURSPALGA" order="83500">Spa. Handball Liga Asobal
    </category>
    AMAYA Sport San Antonio - C.BM.Torrevieja
</description>  

And with the following code I get

Spa. Handball Liga Asobal AMAYA Sport San Antonio - C.BM.Torrevieja

but I want just this:

AMAYA Sport San Antonio - C.BM.Torrevieja

$teams  =   $game->getElementsByTagName("description");
               foreach ($teams as $team)
               {
                     $info      =   $team->nodeValue;
               }

Upvotes: 2

Views: 400

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You need to loop the childNodes of the $team and check if the nodeType == XML_TEXT_NODE

foreach ($teams as $team)
  {
    foreach($team->childNodes as $child)
      {
         if ($child->nodeType == XML_TEXT_NODE && trim($child->nodeValue) != '')
           {
             $info = $child->nodeValue;
             break;
           }
      }
  }

this is beacuse text is also a node (thus the need to loop the childNodes), that has a nodeType value of XML_TEXT_NODE (3)

I am also checking the nodeValue to be non-empty because white-space between nodes can also be treated as textNodes..

Upvotes: 0

Bart
Bart

Reputation: 2060

You need to point to the right node. This node you're pointing to is actually the whole description node, while you need to point to the (implicit) text node containing the string you want.

Solution (provided the string always comes last):

$teams = $xml->getElementsByTagName("description");
foreach ($teams as $team)
{
    $info = $team->lastChild->nodeValue;
    echo "info: $info\n";
}

Upvotes: 2

Related Questions