简体   繁体   中英

Why is this xPath query in PHP not working?

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.

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM