Question

See my PHP:

file = "routingConfig.xml";
global $doc;
$doc = new DOMDocument();
$doc->load( $file );

function traverseXML($ElTag, $attr = null, $arrayNum = 'all'){
    $tag = $doc->getElementsByTagName($ElTag);
    $arr = array();

    foreach($tag as $el){
        $arr[] = $el->getAttribute($attr);
    }
    if ($arrayNum == 'all'){
        return $arr;
    }else if(is_int($arrayNum)){
        return $arr[$arrayNum];
    }else{
        return "Invalid $arrayNum value: ". $arrayNum;
    }; 
}

echo traverseXML("Route", "type", 2);

XML is:

<Routes>
  <Route type="source"></Route>
  <Route></Route>
<Routes>

Error returned is:

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

I'm not sure how to do this?

EDIT: Here is the actual code being used. I originally stripped it a little bit trying to make it easier to read, but I think my problem is related to using the function.

Was it helpful?

Solution

Your problem is that the global $doc; statement is outside the function, so the variable $doc is not defined inside the function.

This would fix it:

// ...
function traverseXML($ElTag, $attr = null, $arrayNum = 'all') {
  global $doc;
// ...

...but

Global variables are bad news. They usually indicate poor design.

Really you should pass $doc in as an argument, like this:

function traverseXML($doc, $ElTag, $attr = null, $arrayNum = 'all'){
    $tag = $doc->getElementsByTagName($ElTag);
    $arr = array();
    foreach($tag as $el){
        $arr[] = $el->getAttribute($attr);
    }
    if ($arrayNum == 'all'){
        return $arr;
    }else if(is_int($arrayNum)){
        return $arr[$arrayNum];
    }else{
        return "Invalid $arrayNum value: ". $arrayNum;
    }; 

}

$file = "routingConfig.xml";

$doc = new DOMDocument();
$doc->load( $file );

echo traverseXML($doc, "Route", "type", 2);

Although you might consider whether you need the function at all - if you don't use it anywhere else in you application, you might as well just do this:

$file = "routingConfig.xml";

$ElTag = "Route";
$attr = "type";
$arrayNum = 2;

$doc = new DOMDocument();
$doc->load( $file );

$tag = $doc->getElementsByTagName($ElTag);
$arr = array();
foreach($tag as $el){
    $arr[] = $el->getAttribute($attr);
}
if ($arrayNum == 'all'){
    echo $arr;
}else if(is_int($arrayNum)){
    echo $arr[$arrayNum];
}else{
    echo "Invalid $arrayNum value: ". $arrayNum;
}; 

OTHER TIPS

The $doc variable is not defined inside your function. You have two options:

  1. Pass $doc as one of the function arguments, which is preferred.

  2. Write global $doc; at the top of your function ... devs usually try to avoid globals.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top