1

I'm new to PHP and stackoverflow. I created a script that takes content from a form and searches for a file list corresponding to the category and subject given. Now, the xPath part throws an error when the script is launched. It says:

Fatal error: Call to a member function getElementsByTagName() on a non-object on line 10.

Here's the code:

if (isset($_GET["subject"])){
    $subject = $_GET["subject"];
    $category = $_GET["category"];
    $doc = new DOMDocument();
    $doc->load('Files.xml');
    $xpath = new DOMXPath($doc);
    //subject
    $subjectpath = 'subject[@name="' . $subject . '"]';
    $ssubjectfiles = $xpath->query($subjectpath)->item(0);
    $subjectfiles = $ssubjectfiles->getElementsByTagName('file');
    //category
    $categorypath = 'subject[@name="' . $subject . '"]/category[@name="' . $category . '"]';
    $scategoryfiles = $xpath->query($categoryfiles)->item(0);
    $categoryfiles = $scategoryfiles->getElementsByTagName('file');
    function getFiles($files){
    foreach($files as $file){
        $filevalue = $file->nodeValue;
        echo '<li>' . $filevalue . '</li>';
    }
    }
    switch($category){
    case 'Select a category or leave to get all the results':
        getFiles($subjectfiles);
    break;
    default:
        getFiles($categoryfiles);
    }
}

Why isn't it working? Do I have to convert the object somehow?

Thank you!


EDIT

It looks like the problem was the relative link. I changed it to http://localhost/Files.xml and it seems to work. Thank you all anyway.

2
  • 2
    There is likely no subject below the root node, but can you show your XML? Commented Nov 6, 2012 at 20:00
  • @Gordon It looks like it. You can try printing the result of every query before doing anything else with them. Commented Nov 6, 2012 at 20:13

1 Answer 1

1

$xpath->query($subjectpath) - return not an empty DOMNodeList, so $xpath->query($subjectpath)->item(0) return null, and then when u call $ssubjectfiles->getElementsByTagName('file'), $ssubjectfiles is null, and here happens error.

plz read manual http://www.php.net/manual/en/book.dom.php

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

2 Comments

Thanks! So it means it didn't find the node?
yes, provide check if this list is empty, and u don't get error in this line.

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.