Alberto Acuña Alberto Acuña - 2 months ago 6
PHP Question

Cant Access Element Using SimpleXML PHP

Okay I have some problems because i cant read some part of my xml:

file.xml

<main>
<a>
<b>
<c>
ok1
</c>
</b>
<b>
<c>
ok2
</c>
</b>
</a>
</main>


I can open the xml file but I cant see the value of 'ok2', hope u can help me, thanks.

file.php

$xml = simplexml_load_file($filename) or die("Error: Cannot create object");


Im trying this:

$xml->{'a'}->{'b'}[1]->{'c'} // but cant see anything


hope u can help, thanks

Answer

You never close the a and you aren't checking for c.

Try:

$xml = new SimpleXmlElement('<main>
 <a>
  <b>
    <c>
      ok1
    </c>
  </b>
  <b>
    <c>
      ok2
    </c>
  </b>
  </a>
</main>');
echo $xml->{'a'}->{'b'}[1]->{'c'};

Demo: https://eval.in/638971

If you wanted it captured cleanly use trim.

echo trim($xml->{'a'}->{'b'}[1]->{'c'});
Comments