How to parse linkedin xml so I get single fields values - php

I have this code:
$xml_response = $linkedin->getProfile("~:(id,firstName,lastName,email-address)");
which generates the following result xml:
<person>
<id>c3g9fdgdbP9-</id>
<first-name>Shoen</first-name>
<last-name>Vergue</last-name>
<email-address>manager#glob....beg.com</email-address>
</person>
How to get for example email value?
I tried this:
$mail=$xml_response['email-address'];
but it returns nothing
Thank you in advance

Check out the SimpleXML Parser, and try something like this:
libxml_use_internal_errors(true);
$xml = simplexml_load_string($xml_response);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
echo $xml->{"email-address"};
}

Related

XML Parsing in PHP (using simplexml_load_string)

I have the following code and I have been working to try to get this working.
<?php declare(strict_types=1);
$session_token = '?'; $xml = '';
$result = '<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://ws.careerbuilder.com/resumes/"><Packet><Errors /><SessionToken>3msk323msd-3312-CQ-2</SessionToken></Packet></string>
';
if ($result) {
$xml = simplexml_load_string($result);
print_r($xml);
if ($xml !== false) {
$session_token = $xml->SessionToken;
echo PHP_EOL.'Session: '. $session_token;
} else {
echo 'Error: XML does NOT appear to be valid';
}
} else
echo 'Error: result does NOT appear be valid';
The problem is no matter what I'm not able to extract the <SessionToken> value from the XML. When I use print_r() I get the following:
SimpleXMLElement Object
(
[0] => <Packet><Errors /><SessionToken>3msk323msd-3312-CQ-2</SessionToken></Packet>
)
Your input is entity-encoded. If this is really what it looks like, you'll need to decode it first:
$xml = simplexml_load_string(html_entity_decode($result));
$token = (string) $xml->Packet->SessionToken[0];
You document contains nested XML. The text content of the string element is serialized XML. So you need to parse it after reading it.
$result = '<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://ws.careerbuilder.com/resumes/"><Packet><Errors /><SessionToken>3msk323msd-3312-CQ-2</SessionToken></Packet></string>
';
$string = new SimpleXMLElement($result);
$packet = new SimpleXMLElement((string)$string);
var_dump($packet);
Output:
object(SimpleXMLElement)#2 (2) {
["Errors"]=>
object(SimpleXMLElement)#3 (0) {
}
["SessionToken"]=>
string(20) "3msk323msd-3312-CQ-2"
}

Get elements from a XML content by PHP

I am trying to get elements from this XML content but returns empty:
<results>
<error>
<string>i</string>
<description>Make I uppercase</description>
<precontext></precontext>
<suggestions>
<option>I</option>
</suggestions>
<type>grammar</type>
</error>
</results>
And this is my code to extract element type of grammar :
$dom = new DOMDocument();
$dom->loadXml($output);
$params = $dom->getElementsByTagName('error'); // Find Sections
$k=0;
foreach ($params as $param) //go to each section 1 by 1
{
if($param->type == "grammar"){
echo $param->description;
}else{
echo "other type";
}
Problem is the script returns empty.
you can use simplexml_load_string()
$output = '<results>
<error>
<string>i</string>
<description>Make I uppercase</description>
<precontext></precontext>
<suggestions>
<option>I</option>
</suggestions>
<type>grammar</type>
</error>
</results>';
$xml = simplexml_load_string($output);
foreach($xml->error as $item)
{
//echo (string)$item->type;
if($item->type == "grammar"){
echo $item->description;
}else{
echo "other type";
}
}
You apparently haven't configured PHP to report errors because your code triggers:
Notice: Undefined property: DOMElement::$type
You need to grab <type> the same way you grab <error>, using DOM methods like e.g. getElementsByTagName(). Same for node value:
if ($param->getElementsByTagName('type')->length && $param->getElementsByTagName('type')[0]->nodeValue === 'grammar') {
// Feel free to add additional checks here:
echo $param->getElementsByTagName('description')[0]->nodeValue;
}else{
echo "other type";
}
Demo
I think is this what you want.
<?php
$output = '<results>
<error>
<string>i</string>
<description>Make I uppercase</description>
<precontext></precontext>
<suggestions>
<option>I</option>
</suggestions>
<type>grammar</type>
</error>
</results>';
$dom = new DOMDocument();
$dom->loadXml($output);
$params = $dom->getElementsByTagName('error'); // Find Sections
$k=0;
foreach ($params as $param) //go to each section 1 by 1
{
$string = $param->getElementsByTagName( "string" )->item(0)->nodeValue;
$description = $param->getElementsByTagName( "description" )->item(0)->nodeValue;
$option = $param->getElementsByTagName( "option" )->item(0)->nodeValue;
$type = $param->getElementsByTagName( "type" )->item(0)->nodeValue;
echo $type;
if($type == "grammar"){
echo $description ;
}else{
echo "other type";
}
}
?>
You're mixing DOM with SimpleXML. This is possible, but you would need to convert the DOM element node into a SimpleXML instance with simplexml_import_dom().
Or you use Xpath. getElementsByTagName() is a low level DOM method. Using Xpath expressions allows for more specific access with a lot less code.
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
foreach ($xpath->evaluate('//error') as $error) {
var_dump(
[
'type' => $xpath->evaluate('string(type)', $error),
'description' => $xpath->evaluate('string(description)', $error)
]
);
}
Output:
array(2) {
["type"]=>
string(7) "grammar"
["description"]=>
string(16) "Make I uppercase"
}
Xpath expressions allow for conditions as well, for example you could fetch all grammar errors using //error[#type = "grammar"].

How to select data from xml file by compare attribute of xml file?

here is my xml file note.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<agents>
<agent>
<id>1</id>
<image> img/primary-nav-logo.png</image>
<name>Tommy Jenkin</name>
<company>CJenkins Insurance</company>
<street>Insurance150 S State Stree</street>
<city>Linkend</city>
<phone>(773) 561-4331</phone>
</agent>
<agent>
<id>2</id>
<image> img/primary-nav-logo.png</image>
<name>Tommy Jenkin</name>
<company>CJenkins Insurance</company>
<street>Insurance150 S State Stree</street>
<city>Linkend</city>
<phone>(773) 561-4331</phone>
</agent>
</agents>
and i have to print xml record of id 1 and i have write code in php like this
<?php
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
foreach($xml->xpath('//agent') as $item) {
$row = simplexml_load_string($item->asXML());
$v = $row->xpath('//id[. ="1"]');
if($v[0]){
print $item->id;
print $item->image;
print $item->name;
print $item->company;
print $item->street;
print $item->city;
print $item->phone;
}
else{
echo 'No records';
}
?>
please suggest me where i am wrong
You do not need to call $item->asXML() since $item is already a SimpleXML object. And you don't have to loop over your array since you can query the necessary agent directly. Try this:
<?php
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
$agent = $xml->xpath('//agent[id=1]');
if (!empty($agent)) {
$item = $agent[0];
print $item->id;
print $item->image;
print $item->name;
print $item->company;
print $item->street;
print $item->city;
print $item->phone;
} else {
echo 'No records';
}
First of all, you are missing the closing bracket of foreach loop.
Second, you can do this with xPath itself.
Look at this code:
<pre><?php
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
$item = $xml->xpath('//agents/agent[id=1]')[0];
if($item!=null){
print_r($item);
}else{
echo "No Records";
}
?></pre>

DomNode get value of item

Hello I'm new with domnode and i'm trying to check the values from an xml tree which loads ok.
Here is my code but I dont understand why is not working.
private function createCSV($xml, $f)
{
foreach ($xml->getElementsByTagName('*') as $item)
{
$hasChild = $item->hasChildNodes() ? true : false;
if(!$hasChild)
{
//echo 'Doesn\'t have children';
echo 'Value: ' . $item->nodeValue;
}
else
{
//echo 'Has children';
$this->createCSV($item, $f);
}
}
}
$item->nodeValue doesnt print anything to the browser.
I read the documentation but I can't see any mistake.
PS. $item->tagname doesnt work either.
UPDATE
whe using this: echo $item->ownerDocument->saveHTML($item);
I get the tags listed but i dont get the data inside(between the tags) like innerHTML in javascript.
UPDATE
sample xml data : http://pastebin.com/dkuUUC0Q
Text nodes are also considered child nodes, but you're only iterating element nodes (get Elements ByTagName). Because of this you're almost never getting into the 2nd condition.
Try this:
if(!$xml->hasChildNodes()){
printf('Value: %s', $xml->nodeValue);
return;
}
foreach($xml->childNodes as $item)
$this->createCSV($item, $f);
XPath version:
$xpath = new DOMXPath($xml);
$text = $xpath->query('//text()[normalize-space()]');
foreach($text as $node)
printf('Value: %s', $node->nodeValue);

Troubleshooting parsing of XML document using PHP SimpleXml

I've used xpath to process XML element before, however I'm struggling to get the syntax right for this particular XML.
I'm trying to parse a guardian API response. Sample response:
<response user-tier="approved" current-page="1" start-index="1" page-size="10" pages="1" total="10" status="ok">
<results>
<tag type="series" web-title="Cycling" section-name="Life and style" id="lifeandstyle/series/cycling" api- url="http://content.guardianapis.com/lifeandstyle/series/cycling" section-id="lifeandstyle" web- url="http://www.guardian.co.uk/lifeandstyle/series/cycling"/>
<tag type="keyword" web-title="Cycling" section-name="Sport" id="sport/cycling" api- url="http://content.guardianapis.com/sport/cycling" section-id="sport" web- url="http://www.guardian.co.uk/sport/cycling"/>
<tag type="keyword" web-title="Cycling" section-name="Life and style" id="lifeandstyle/cycling" api-url="http://content.guardianapis.com/lifeandstyle/cycling" section-id="lifeandstyle" web-url="http://www.guardian.co.uk/lifeandstyle/cycling"/>
<results>
<response>
Here is my first try coding it in PHP (I've connected using cURL):
$news_items = new SimpleXMLElement($result); //loads the result of the cURL into a simpleXML response
$news_items = $guardian_response->xpath('results');
foreach ($news_items as $item) { //for each statement every entry will load the news_item and the web_url for the document
$item_block = "<p class=\"web_title\">";
$item_block = "<p class=\"web_url\">";
}
It doesn't retrieve anything, is there any flaws in my code?
<?php
function getAttribute($object, $attribute) {
foreach($object->attributes() as $a => $b) {
if ($a == $attribute) { $return = $b; }
}
if($return) { return $return; }
}
try {
$xml = simplexml_load_file( "parse.xml" );
/* Pay attention to the XPath, include all parents */
$result = $xml->xpath('/response/results/tag');
while(list( , $node) = each($result)) {
echo getAttribute( $node, "type" );
}
} catch( Exception $e ) {
echo "Exception on line ".$e->getLine()." of file ".$e->getFile()." : ".$e->getMessage()."<br/>";
}
?>

Categories