getting attributes in simplexml_load_string - php

Below is the function which i am using to convert xml to array
$xml = '<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>';
$obj = simplexml_load_string($xml); // Parse XML
$obj->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
$array = json_decode(json_encode($obj), true); // Convert to array
when i try with the parent node "xml"
<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>
i get this result
Array
(
[CodeshareInfo] => ETIHAD AIRWAYS
)
but if i try without parent node "xml"
<CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo>
i can get the attributes and the value
Array
(
[#attributes] => Array
(
[OperatingCarrier] => EY
[OperatingFlightNumber] => 269
)
[0] => ETIHAD AIRWAYS
)
what should i change in code to get the output with attributes and values as my xml data is from a soap request and once i receive i will convert as array to access its value and attributes.

Given the provided XML you can iterate through it and pull out the attributes and values.
<?php
$xml = '<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>';
$obj = simplexml_load_string($xml); // Parse XML
$obj->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
foreach($obj as $ob) {
echo $ob['OperatingCarrier'] . "\n";
echo $ob . "\n";
echo $ob['OperatingFlightNumber'] . "\n";
}
Output:
EY
ETIHAD AIRWAYS
269

Related

Access 0 index xml property in php

I have written a program which read an XML file and provide me an array. So I further perform my operations but I am not able to get the value of 0 index.
$xml = simplexml_load_file("app_string.xml");
foreach ($xml as $value) {
echo "<pre>";
print_r($value);
}
That is the output:
SimpleXMLElement Object (
[#attributes] => Array
(
[name] => app_name
)
[0] => My Data )
I tried with
$value->{0}
and
$value['0']
Not getting the desire data.
How can I get My Data from [0] => My Data
To retrieve the element data, you can simple cast the XML element to a string, as in:
$xml = simplexml_load_file("app_string.xml");
foreach ($xml as $value) {
echo "<pre>";
$data = (string)$value;
echo $data;
}

simplexml_load_file() does not getting node content

I cannot get XML node contents and attributes at the same time with SimpleXML library:
I have the following XML, and want to get content#name attribute and node's contents:
<page id="id1">
<content name="abc">def</content>
</page>
Method simplexml_load_string()
print_r(simplexml_load_string('<page id="id1"><content name="abc">def</content></page>'));
outputs this:
SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => id1
)
[content] => def
)
As you can see, contents of the content node is present, but attributes are missing. How can I receive the contents and attributes?
Thanks!
The attributes of content are present. This is just a trick of print_r() and how it works with XML objects in memory.
$x = simplexml_load_string('<page id="id1"><content name="abc">def</content></page>');
print_r($x->content);
print_r($x->content['name']);
SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => abc
)
[0] => def
)
SimpleXMLElement Object
(
[0] => abc
)
In simplexml, accessing elements returns SimpleXMLElement objects. You can view the content of these objects using var_dump.
$book=simplexml_load_string('<page id="id1"><content name="abc">def</content></page>');
$content=$book->content;
var_dump($content);
You can access these objects with foreach loop.
foreach($obj as $value) {
if (is_array($value)) {
foreach ($value as $name=>$value) {
print $name.": ".$value."\n";}
}
else print $value;
}
You can not only retrieve contents (such as elements and attributes) but also add and remove them. You can also use Xpath to navigate values in complex XML tree. You just need to go through the methods of SimpleXMLElement class here.
$x = simplexml_load_string('<page id="id1"><content name="abc">def</content></page>');
To get the node's attributes:
$attributes = $x->content->attributes(); //where content is the name of the node
$name = $attributes['name'];
To get the content node's content:
$c = $x->content;
Interesting, that $c can be used as string and as object, i.e.
echo $c; //prints string
print_r($c) //prints it out as object

How can I extract value from an xml

I'm new to PHP. I'm trying to get the data out of the below XML. Now, in my code $data->Address contains value of the below code i.e:
$data->Address = "<tolist></tolist>
<cclist>
<cc>
<contactpersonname>niraj</contactpersonname>
<name>niraj</name>
<email>stgh#gmail.com</email>
<number>+91.3212365212</number>
<prefix>Ms.</prefix>
<contactpersonprefix>Ms.</contactpersonprefix>
</cc>
<cc>
<contactpersonname>fdg</contactpersonname>
<name>admin</name>
<email>admin12#gmail.com</email>
<number>+91.4554343234</number>
<prefix>Mr.</prefix>
<contactpersonprefix>Mr.</contactpersonprefix>
</cc>
</cclist>";
Now I want to extract the <contactpersonname> tag and print it. How can I do this?
Since your XML is missing a tag that encompasses all others, you need to create on in order to get parsers to work properly:
<?php
$buffer = "<tolist></tolist>
<cclist>
<cc>
<contactpersonname>niraj</contactpersonname>
<name>niraj</name>
<email>stgh#gmail.com</email>
<number>+91.3212365212</number>
<prefix>Ms.</prefix>
<contactpersonprefix>Ms.</contactpersonprefix>
</cc>
<cc>
<contactpersonname>fdg</contactpersonname>
<name>admin</name>
<email>admin12#gmail.com</email>
<number>+91.4554343234</number>
<prefix>Mr.</prefix>
<contactpersonprefix>Mr.</contactpersonprefix>
</cc>
</cclist>";
// ***** wrap the whole thing in a <root> tag...
$xml = simplexml_load_string("<root>".$buffer."</root>");
$array = json_decode(json_encode((array) $xml), 1);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
Result:
Array
(
[tolist] => Array
(
)
[cclist] => Array
(
[cc] => Array
(
[0] => Array
(
[contactpersonname] => niraj
[name] => niraj
[email] => stgh#gmail.com
[number] => +91.3212365212
[prefix] => Ms.
[contactpersonprefix] => Ms.
)
[1] => Array
(
[contactpersonname] => fdg
[name] => admin
[email] => admin12#gmail.com
[number] => +91.4554343234
[prefix] => Mr.
[contactpersonprefix] => Mr.
)
)
)
)
UPDATED
Now you can navigate down to where you want to go with
echo "<pre>";
$ccList = $array['cclist'];
$cc = $ccList['cc'];
$contacts = array();
foreach($cc as $i=>$val) {
$contacts[$i]=$val['contactpersonname'];
}
echo "first contact: " . $contacts[0] . "<br>";
echo "second contact: " . $contacts[1] ."<br>";
Result:
first contact: niraj
second contact: fdg
You can convert the XML to an array with the following code:
$xml = simplexml_load_string($buffer);
$array = json_decode(json_encode((array) $xml), 1);
Where $buffer is the xml string.
Then you can obtain the person name as follow:
$data->Address = $array['cclist']['cc']['contactpersonname'];
It's a quick and dirty method to convert the xml to an array, but it works.
Try this..
$xml = new SimpleXMLElement($string);
$results = $xml->xpath('cclist/cc/contactpersonname');
http://php.net/manual/en/simplexmlelement.xpath.php
$xml = simplexml_load_file("note.xml");
echo $xml->contactpersonname;
This requires you to load it form an xml file. If you already have the string in the code I'd recommend a regex. If you know the data won't ever be incorrect written!
$pattern = '#<contactpersonname>(.*?)</contactpersonname>#';
echo preg_match ($pattern, $data->Address);

Extracting data from xpath reference of SimpleXMLElement Object

I'm trying to read an XML file into an array and I'm having a little bit of trouble. Here is what my code looks like so far:
$inst = new SimpleXMLElement($xml);
foreach( $inst->xpath("record[#id='" . $range . "']") as $u ) {
foreach($fields as $field) {
$results[$field] = $u->$field;
}
}
But when I do print_r($results), this is what's outputted:
Array
(
[field1] => SimpleXMLElement Object
(
[0] => field1Data
)
[field2] => SimpleXMLElement Object
(
[0] => field2Data
)
[field3] => SimpleXMLElement Object
(
[0] => field3Data
)
)
How can I get the data straight from the SimpleXMLElement Object and store it in the array rather than having it do this? I tried accessing it as an array like $u->$field[0] but that didn't work either.
Casting a SimpleXMLElement to string is the general solution(see "Forcing a SimpleXML Object to a string, regardless of context" for the canonical question), for a complete array containing all SimpleXMLElements like returned by xpath() or like you create it your own, a common way is to map the array onto trim:
$results = array_map('trim', $results);
or strval:
$results = array_map('strval', $results);
For example:
$inst = new SimpleXMLElement($xml);
list($u) = $inst->xpath("record[#id='" . $range . "']")
foreach ($fields as $field) {
$results[$field] = $u->$field;
}
$results = array_map('strval', $results);

SimpleXML and XML collections - how to get the attribute value as an array key?

I'm just trying to figure out how to cleanly and nicely transform a XML collection into an appropriate object. See, I've got this very simple XML string :
$x = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<apiKeys>
<apiKey application="app1">HfxaoMBJJ9pLe</apiKey>
<apiKey application="app2">HfxaoMBJJ9pLeClsSHsh</apiKey>
<apiKey application="app3">HfxaoMBJJ9pLeClsSHshTI9qX</apiKey>
</apiKeys>';
Which I transform using :
$O_xmlElement = simplexml_load_string ($x);
This is what I get :
SimpleXMLElement Object
(
[apiKey] => Array
(
[0] => HfxaoMBJJ9pLe
[1] => HfxaoMBJJ9pLeClsSHsh
[2] => HfxaoMBJJ9pLeClsSHshTI9qX
)
)
And I'd rather have (I expected !) something like :
SimpleXMLElement Object
(
[apiKey] => Array
(
['app1'] => HfxaoMBJJ9pLe
['app2'] => HfxaoMBJJ9pLeClsSHsh
['app3'] => HfxaoMBJJ9pLeClsSHshTI9qX
)
)
Thank you very much for your help people
SimpleXML won't do what you want automatically. You'll have to build the object yourself:
$O_xmlElement = simplexml_load_string($x);
$myObject = new stdClass();
foreach ($O_xmlElement->apiKey as $apiKey) {
$key = (string) $apiKey['application'];
$myObject->${key} = (string) $apiKey;
}
Refer to the basic usage example in the PHP manual for good examples of dealing with child elements and attributes.
When getting attributes from a SimpleXMLElement, remember that each attribute will be a SimpleXMLElement and not a string. You'll want to explicitly cast each attribute to string before using it as an array key or object property name.
Not sure you can do it exactly as you want it, but you can check out php.net's docs here:
http://www.php.net/manual/en/simplexmlelement.attributes.php
Basically the attributes can be found inside an object attached to each of the apiKey objects.
You can use the following code:
$xml = simplexml_load_string($x);
$newArray = array();
$count=0;
foreach($xml as $value){
$key= (string)($xml->apiKey[$count++]->attributes()->application);
$newArray[$key] = $value[0];
}
$newArray = array_map("trim", $newArray);
print_r($newArray);
This will generate the following output:
Array
(
[app1] => HfxaoMBJJ9pLe
[app2] => HfxaoMBJJ9pLeClsSHsh
[app3] => HfxaoMBJJ9pLeClsSHshTI9qX
)

Categories