Reputation: 27
Can you help me? I'm facing a strange problem when parsing my XML.
Here is my PHP script:
$xml = "https://pastebin.com/raw/30QHhFSr";
$response = new SimpleXMLElement(file_get_contents($xml)) or die('error');
$auto = "ENDS->E0->ENDERECO";
echo $response->$auto; //output: nothing
echo $response->ENDS->E0->ENDERECO; //output: SAO SEVERINO //works
Why $response->$auto;
is not working?
Thank you.
Upvotes: 1
Views: 49
Reputation: 6388
->, is used when you want to call a method on an instance or access an instance property
SimpleXMLElement - Represents an element in an XML document.
$response
is an instance of SimpleXMLElement
, You need to define like this
$level1 = "ENDS";
$level2 = "E0";
$level3 = "ENDERECO";
Now you can retrieve the value using
$response->$level1->$level2->$level3;
Upvotes: 0
Reputation: 41885
What getting is correct since your arrow notation is actually a string literal, which in itself doesn't do anything when you do:
$auto = "ENDS->E0->ENDERECO";
echo $response->$auto;
echo $response->{"ENDS->E0->ENDERECO"}; // it doesn't really exist
The alternative is you can process the string and break it down using explode
, and use array reduce.
Here's the idea:
$xml = 'https://pastebin.com/raw/30QHhFSr';
$response = new SimpleXMLElement(file_get_contents($xml)) or die('error');
$auto = 'ENDS->E0->ENDERECO';
echo array_reduce(explode('->', $auto), function ($o, $p) {
return $o->$p;
}, $response);
Upvotes: 1