0

I'm trying to use XPath with PHP and I can't get it to simply return a value. Could someone please let me know what I'm doing wrong?

The result I get is:

Array ( [0] => SimpleXMLElement Object ( ) )

but W3Schools says the result is supposed to be:

Array
(
[0] => SimpleXMLElement Object
  (
  [0] => Jani
  )
)

Here's what I'm using:

XML:

<?xml version="1.0" encoding="UTF-8"?>
  <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
  </note>

PHP:

<?php
    $XMLfile = "test.xml";

    $xml = simplexml_load_file($XMLfile);
    $result = $xml->xpath("from");
    print_r($result);
?>
1
  • How about simply echo $xml->from? Commented Feb 19, 2014 at 2:31

1 Answer 1

1

Nobody is getting it. But I know what you are missing JaceG.

You are expecting print_r to show you 'Jani', but neither var_dump or print_r will show you 'Jani'.

Please add this after your print_r to test.

foreach ($result as $le_result)
      echo $le_result;

And there will be 'Jani'.

Neither var_dump or print_r, display useful output on DOM Objects. You have to look at them yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

Just to elaborate on why OP's expression works (since I found it surprising): simplexml_load_file($XMLfile) returns a reference to the root element, not the document itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.