2

I'm trying to filter my XML file for an element with a specific name. I've followed the instructions from here but the result is empty everytime.

XML

<vertalingen>
    <kamers>
        <kamer>
            <naam>Bruidssuite</naam>
            <beschrijving>Lorum Ipsum</beschrijving>
        </kamer>
    </kamers>    
</vertalingen>

PHP

$xml = simplexml_load_file('translations/nederlands.xml');
$info = $xml->xpath('//kamer[naam="Bruidssuite"]');
echo " found {$info->naam}";

The code only returns "found"

The code gives the following PHP error:

PHP Notice: Trying to get property of non-object

I've also tried the following variations:

$info = $xml->xpath('/vertalingen/kamers/kamer[naam="Bruidssuite"]');
$info = $xml->xpath('/kamers/kamer[naam="Bruidssuite"]');
hakre
  • 193,403
  • 52
  • 435
  • 836
Orynuh
  • 105
  • 1
  • 10
  • 1
    The code in your question gives the following error: ***PHP Notice: Trying to get property of non-object***. When you write PHP code you should have all errors in PHP given to you: That is strict warnings, infos, warnings, notices, errors etc. pp. Just enable error logging to the highest level, enable display errors and log errors to file. Then PHP will often tell you about the places you've some little mistakes which will either help you right away or asking better questions. Debugging questions with shifted contexts aren't of much interest in a Q&A for future users. – hakre Apr 03 '15 at 03:08

1 Answers1

2

That XPath query returns several elements. The return value of xpath() is an either an array (on success) or FALSE (on error),

From the php.net manual:

Returns an array of SimpleXMLElement objects or FALSE in case of an error.

Try the following:

$kamers = $xml->xpath('//kamer[naam="Bruidssuite"]');

foreach($kamer as $kamers) {
    echo "Found {$kamer->naam}<br />";
}

Or just get the first element if you are sure the property naam is unique:

$info = $xml->xpath('//kamer[naam="Bruidssuite"]');
echo " found {$info[0]->naam}";
helb
  • 7,609
  • 8
  • 36
  • 58