rmmoul
rmmoul

Reputation: 3217

cant get values from xml with php

I must be missing something simple here and it's driving me crazy.

I'm making a call to a web services api and getting back some xml:

<?xml version="1.0" encoding="utf-16"?>
<MTSMember xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <LastName>Smith</LastName>
  <FirstName>john</FirstName>
  <MemberNo>xxxxxxxx</MemberNo>
  <Club>None</Club>
  <JoinDate>2013-05-14</JoinDate> 
  <Email>[email protected]</Email>
</MTSMember>

I then need to process this xml to get the email address. but I'm just getting an empty result using the code below:

$xml_result = simplexml_load_string($xml_string_above);
echo $xml_result->MTSMember[0]->Email;

Can someone point me in the right direction. I've read through several other answers trying out various solutions, but can't seem to get it to work.

Edit: This was the last tutorial i tried out http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

Upvotes: 0

Views: 62

Answers (3)

LefterisL
LefterisL

Reputation: 1153

This should work fine

$xml = new SimpleXMLElement($xml_string_above);

$dc = $xml->email;
echo $dc;

Upvotes: 0

internals-in
internals-in

Reputation: 5038

Try this

$xml=new SimpleXMLElement($str);
$result=$xml->xpath('//Email');
foreach ($result as $Email)
  echo $Email . "<br>";

simply

$xml=new SimpleXMLElement($str);
echo $xml[0]->Email;

update:

The below just for your comment , the whole what i tried

$str='<?xml version="1.0" encoding="utf-8"?>
<MTSMember xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <LastName>Smith</LastName>
  <FirstName>john</FirstName>
  <MemberNo>xxxxxxxx</MemberNo>
  <Club>None</Club>
  <JoinDate>2013-05-14</JoinDate> 
  <Email>[email protected]</Email>
</MTSMember>';

$xml=new SimpleXMLElement($str);
echo $xml[0]->Email;
 //OR
$xml=new SimpleXMLElement($str);
$result=$xml->xpath('//Email');
foreach ($result as $Email)
  echo $Email . "<br>";

Be happy :)

Upvotes: 0

Mihai Iorga
Mihai Iorga

Reputation: 39724

That should be:

echo $xml_result->Email;

Because simplexml_load_string() is loading MTSMember as main SimpleXMLElement.

Codepad Example

Upvotes: 2

Related Questions