Reputation: 4091
I'm retrieving an xml:
$xml = file_get_contents($query);
echo $xml->Email;
echo $xml[0]->Email;
The xml (echo $xml) looks like this:
<GetUserInfo>
<Customer>TestUser</Customer>
<Email>[email protected]</Balance>
</GetUserInfo>
But both those approaches give the following error:
Notice: Trying to get property of non-object in test.php on line 86
Notice: Trying to get property of non-object in test.php on line 87
How can I get the value of Email and Customer?
Upvotes: 1
Views: 2726
Reputation: 3049
Your $xml
is a string. $xml->
accesses a property of an object. That is not compatible. A php string is not an object.
You may want to use var_dump()
instead of echo()
to see all the details of your variables.
A simple string to object convertor is simplexml_load_string()
$xml='
<GetUserInfo>
<Customer>TestUser</Customer>
<Email>[email protected]</Email>
</GetUserInfo>
';
var_dump($xml);
$Xml = simplexml_load_string($xml);
var_dump($Xml);
echo($Xml->Email);
Upvotes: 3
Reputation: 3507
file_get_contents()
returns the file content, not an object. You can only use preg_match
if you want to stick to string content (totally not advised):
preg_match('~<Email>([^<]+)</Email>~i', file_get_contents($__filePath__), $emails);
I recommend using DOMDocument
and DOMXPath
(code not tested):
$XMLDoc = new DOMDocument();
$XMLDoc->load($__filePath__);
$XPath = new DOMXPath($XMLDoc);
$emails = $XPath->query('//email');
foreach ($emails as $email)
var_dump($email->nodeValue);
You might use another Xpath expression like //email[1]
or /GetUserInfo/Email
The foreach may also be replaced by $email = reset($emails);
if you only want the first mail.
Upvotes: 3