PHP get XML node attributes when value exist

I want get the whole XML contents, but the results only show node value, node attributes are missing.

XML File:

<main> <people num="1"> <name num1="1">Jack</name> <age num2="1">50</age> </people> </main>

The code is

$xml = simplexml_load_file("c:/www/Mongo/test2.xml"); $xml1=$xml->people; var_dump($xml1);

Result:

object(SimpleXMLElement)#2 (3) { ["@attributes"]=> array(1) { ["num"]=>string(1) "1" } ["name"]=> string(4) "Jack" ["age"]=> string(2) "50" }

Name&Age node attributes are missing. I know the attributes could get by $xml->people->name, but how to get it only use $xml->people

--------------Solutions-------------

The problem is that leaf nodes (e.g. name) can have both attributes (num1 = "1") and a value ("Jack"). Just how should that be represented when converted into an array?

If we set $array['people']['name'] = "Jack", where would we store the attributes? We cannot use $array['people']['name']['@attributes'] = ['num1' => 1] as that would overwrite the "Jack" value.

The code below presents one solution, where each (leaf) value is wrapped in a 'value' element, e.g. $array['people']['name']['value'] = "Jack" and the attributes have the standard '@attributes' key, e.g. $array['people']['name']['@attributes'] = ['num1' => 1]. This would work for simple XML like the one in your question but may not be suitable for more complicated documents.

Reading the comments I understand that you actually want to convert the XML into JSON, so that is what the following code does in the end:

// Some example XML (some elements added)
$src = <<<EOS
<main>
<people num="1">
<name num1="1">Jack</name>
<age num2="1">50</age>
<skills what="ever">
<skill type="minor">Cookie munching</skill>
<skill type="major">Cake gobbling</skill>
<skill>Candy gulping</skill>
</skills>
</people>
</main>
EOS;

// Create a DOM element from XML
$dom = new DOMDocument();
$dom->loadXML($src);

// Use a XPath query to get all leaf nodes (elements without
// element child nodes)
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//*[not(*)]') as $leaf) {
// Create a new <value> element for each leaf node, moving
// the leaf value (first child) into that node.
// E.g. <name num1="1">Jack</name>
// => <name num1="1"><value>Jack</value></name>
$value = $dom->createElement('value');
$value->appendChild($leaf->firstChild);
$leaf->insertBefore($value);
}

// Turn into SimpleXMLElement and covert to JSON
$xml = simplexml_import_dom($dom);
$json = json_encode($xml, JSON_PRETTY_PRINT);
echo $json, PHP_EOL;

Output:

{
"people": {
"@attributes": {
"num": "1"
},
"name": {
"@attributes": {
"num1": "1"
},
"value": "Jack"
},
"age": {
"@attributes": {
"num2": "1"
},
"value": "50"
},
"skills": {
"@attributes": {
"what": "ever"
},
"skill": [
{
"@attributes": {
"type": "minor"
},
"value": "Cookie munching"
},
{
"@attributes": {
"type": "major"
},
"value": "Cake gobbling"
},
{
"value": "Candy gulping"
}
]
}
}
}

Here is a better solution using json_encode, json_decode

echo '<pre>';
$xml = simplexml_load_file("n.xml");
$xml=json_decode(json_encode($xml),TRUE);
$xml1=$xml['people'];
print_r($xml1);
echo '<br>';
print_r($xml['people']['@attributes']['num']);

Output:

Array
(
[@attributes] => Array
(
[num] => 1
)

[name] => Jack
[age] => 50
)

1

So one last suggestion , probably you can change your XML data something like this

<?xml version="1.0" encoding="UTF-8"?>
<main>
<people num="1">
<name num1="1"><first_name>Jack</first_name></name>
<age num2="1"><years>50</years></age>
</people>
</main>

Output:

Array
(
[people] => Array
(
[@attributes] => Array
(
[num] => 1
)

[name] => Array
(
[@attributes] => Array
(
[num1] => 1
)

[first_name] => Jack
)

[age] => Array
(
[@attributes] => Array
(
[num2] => 1
)

[years] => 50
)

)

)

this should work for you. :)

Category:php Time:2017-12-03 Views:2
Tags: php simplexml

Related post

  • Problem getting XML node attribute value with nokogiri 2011-01-24

    I'm trying to parse an XML file from iTunes using nokogiri and rails 3. Here is my code: itunes_top_300 = Nokogiri.HTML(open("http://itunes.apple.com/us/rss/toppodcasts/limit=300/xml")) itunes_top_300.search('//entry').each do |podcast| url = podcast

  • Getting XML node attributes 2011-11-03

    I'm using a custom XML parser here after getting a file via cURL. here's the parsing function function pd_xml_parser($rawxml) { $xml_parser = xml_parser_create(); xml_parse_into_struct($xml_parser, $rawxml, $vals, $index); xml_parser_free($xml_parser

  • In C#, how to get XML node value that is white space? 2009-12-18

    I have a XML node with a value which is a white space. Example: <sampleNode> </sampleNode> I am using a Serializer to get the data from XML document to store it in an object. Now, the problem I am facing is: If the XML node value contains

  • How to get root node attributes on java 2011-01-19

    I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do. <pharmacies

  • How to to get xml element using element value? 2015-02-09

    I need to get xml element using element value and I have to get parent element with xml element using jaxb? sample XML: <ifx> <nam-ref>LID</nam-ref> <val>01</val> <then> <int> <name>WHEELSPEED</name

  • Getting root node attribute, jQuery/XML 2010-02-22

    this is probably so trivial that I'm ashamed to be asking this... Why in the world is this not working? <?xml version="1.0" encoding="UTF-8"?> <filter id="4" max_values="10"> <value id="9">strategy</value> <value id="11"

  • PHP retrieve xml node value with simplexml 2011-06-11

    Possible Duplicate: PHP SimpleXML get innerXML I've seen others questions related to simplexml and node value but couldn't find an answer to my problem. I have a PHP var which contains an xml document formed like that : <div id="container">

  • Check if node with attribute equals value exists 2011-12-07

    I have the following XSLT variable: <xsl:variable name="superid" select="/contentdata/id"/> Furthermore, I have a node with subnodes: <nodes> <node name="foo" id="bar" /> <node name="john" id="doe" /> <node name="jane" id="

  • how to get root node attribute value using linq 2009-10-09

    I have the following XML. How to read the root node attribite value and it's decendents using LINQ? I am trying to read "dId" and "dTime" from root node, "id" from Customer element and Order number. <?xml version="1.0" encoding="utf-8" ?> <C

  • Get xml node value as string C# 2011-10-05

    I've been trying to pull the value of the XML node into a string. Here is what the XML looks like: <currentvin value="1FTWW31R08EB18119" /> I can't seem to figure out how to grab that value. I didn't write this XML, by the way. So far I have tr

  • PHP - DOM - XML - Nodes with similar attribute manipulation 2012-02-23

    I have to manipulate a XML file with DOM This is my situation: <mainnode> <node1 name="aaa"> <subnode name="123456" /> </node1> <node1 name="bbb"> <subnode name="28472" /> </node1> <node1 name="aaa">

  • Difference and usage best practice of XML node value and XML node attribute 2011-09-02

    I see the following simple XML. <?xml version="1.0"?> <customers> <customer ID="C001"> <name>Acme Inc.</name> <phone>12345</phone> </customer> <customer ID="C002"> <name>Star Wars Inc.</n

  • Select SQL Query to get xml node values from ntext column? 2011-09-12

    I want to get one xml node value from NTEXT column which contains xml based on where clause quering on another xml node value. RDBMS Type: Microsoft SQL Server T-SQL Here: I want to get Code node value based on StoreId where clause value. How do I ge

  • php in array returning false when value does exist 2011-03-17

    Simple one here, but hurting ones head. echo in_array('275', $searchMe); is returning false. But if I print the array out and then search it manually using my web browser I am able to see that the value exists in the array. [0] => ExtrasInfoType O

  • PHP5 and DOM changing XML node attribute value 2012-04-24

    Having the next XML(Idatzi.xml) : <?xml version='1.0' encoding='ISO-8859-1'?> <!DOCTYPE markables SYSTEM "markables.dtd"> <markables> <markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable> <markable

  • PHP - Duplicate XML node using Simple XML 2010-03-01

    I need to load an XML source using Simple XML, duplicate an existing node with all his children, then customize an attribute of this new node before rendering XML. Any suggestion? --------------Solutions------------- SimpleXML can't do this, so you'l

  • Get root node attributes 2010-01-29

    I have an XML document with a basic structure like this: <?xml version="1.0" encoding="UTF-8" ?> <records timestamp="1264777862"> <record></record> <record></record> <record></record> <record><

  • get xml node by order 2011-02-09

    i have the xml file like: <?xml version="1.0" encoding="utf-8" ?> <Config> <MetadataFormConfig FieldInternalName="Test"> <Tabs> <Tab Title="A to C" Order="1"> <ShowParentTerm>A</ShowParentTerm> <ShowParent

  • Detecting existence of empty XML node attribute with XPathNavigator 2011-06-14

    Is there an easy way to detect the existence of an empty attribute on an XPathNavigator XML node (e.g. <node> vs. <node attribute="">)? Node.GetAttribute returns an empty string either way. The only thing I can think of is checking the No

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.414 (s). 13 q(s)