0

I have a function which is trying to get text from XML using XPath query.The function reads:

function getInterviewText($id)  {
    $sxe = simplexml_load_file("./interview2.xml");
    foreach($sxe->xpath('//interview') as $item) {
        $row = simplexml_load_string($item->asXML());
        $v = $row->xpath('//interview-id[.="$id"]');
        if($v[0]) {
            echo '<interview-text>'.$item->INTERVIEW-TEXT.'</interview-text>' 
        }
    }
}

The XML File reads:

<?xml version="1.0"?>
<ROOT>
    <interview>
        <interview-id>1</interview-id>
        <INTERVIEW-TEXT>                                
            Test1
        </INTERVIEW-TEXT>
    </interview>
    <interview>
        <interview-id>2</interview-id>
        <INTERVIEW-TEXT>                              
            Test2          
        </INTERVIEW-TEXT>
    </interview>
</ROOT>

However, the function is not returning anything, when I am trying to call it with id=1 or 2. Any help is greatly appreciated.

Thanks

1 Answer 1

1

The problem is here:

$v = $row->xpath('//interview-id[.="$id"]');

$id is not being expanded because you are within a single-quoted string. Try one of the following instead:

$v = $row->xpath('//interview-id[.="' . $id . '"]');
// Or
$v = $row->xpath("//interview-id[.=\"{$id}\"]");
Sign up to request clarification or add additional context in comments.

1 Comment

But watch out for code injection attacks if $id is a value entered by the user.

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.