Not displaying array elements by index - php

I wrote a php code for retrieving some data from a XML file into a variable.
This is the XML file:
<Server>
<Server1>
<ipaddress>10.3.2.0</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.1</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.2</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.3</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
</Server>
This is the PHP code:
$x = $xmlDoc->getElementsByTagName("ipaddress");
Here i want to display the content of $x by index value, something like
echo $x[0]->nodeValue;
How could I do that?

I assume you used DOMDocument for the XML parsing. When invoking getElementsByTagName you will receive a DOMNodeList not an array.
DOMNodeList implements Traversable so it can be used in foreach loops.
foreach ($x as $item) {
var_dump($item->nodeValue);
}
If you just want a specific item use the item method.
$x->item(0)->nodeValue;

You can access ipaddress like below.
$xml = simplexml_load_file("yourxml.xml");
$result = $xml->xpath('//Server1');
foreach($result as $item){
echo "IP Address:".$item->ipaddress
echo "<br/>";
}

The demo.
$xml = simplexml_load_file($path_to_your_xml_file);
foreach($xml->Server1 as $server) {
echo $server->ipaddress . '<br>';
}
Or you could just do:
echo $xml->Server1[0]->ipaddress;

Related

Missing children in XML parsed by SimpleXML in PHP

Here is the XML I am parsing:
https://seekingalpha.com/api/sa/combined/AAPL.xml
When I grab and parse the XML with simplexml_load_file($url) and then do a var_dump on that, it shows that the only children of every "item" are "title", "link", "guid", and "pubDate."
I am trying to access the node "sa:author_name." Why isn't it a child of "item"? Maybe I am misunderstanding something about how XML files are structured. Help me my children are missing lol
To get the data in sa:author_name you have to use the namespace https://seekingalpha.com/api/1.0.
You can for example use a foreach and loop the children using the namespace.
$url = "https://seekingalpha.com/api/sa/combined/AAPL.xml";
$xml = simplexml_load_file($url);
foreach ($xml->channel->item as $item) {
foreach ($item->children("https://seekingalpha.com/api/1.0") as $child) {
if ($child->getName() === "author_name") {
echo $child . "<br>";
}
}
}
Another way you could do it is using an xpath expression:
$authorNames = $xml->xpath('/rss/channel/item/sa:author_name');
foreach ($authorNames as $authorName) {
echo $authorName . "<br>";
}
Which will result in:
Yoel Minkoff
DoctoRx
SA Transcripts
Bill Maurer
etc..

foreach loop for xml

I have following xml getting loaded in my PHP code;
<SiteAlarmDetails>
<AlertId>89637</AlertId>
<SiteCode>20157498</SiteCode>
<SiteName>newport</SiteName>
</SiteAlarmDetails>
$alertXml = simplexml_load_string( $tableAlarm->AlarmDetails);
echo (string) $alertXml->AlertId; //prints **89637**
Now I try to traverse this XML nodes;
foreach($alertXml->children() as $alerts)
{
$alertId = (string)$alerts->AlertId;
echo $alertId;//I do not see anything
}
Is above right approach to traverse AlertId in the foreach loop?
Trying simple foreach will be helpful. Just for accessing single value (eg AlertId) you can use $alertXml->AlertId;.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$xmlString=<<<XML
<SiteAlarmDetails>
<AlertId>89637</AlertId>
<SiteCode>20157498</SiteCode>
<SiteName>newport</SiteName>
</SiteAlarmDetails>
XML;
$alertXml = simplexml_load_string( $xmlString);
foreach($alertXml as $key => $child)
{
echo $key ."=".(string)$alertXml->{$key};
echo PHP_EOL;
}
Output:
AlertId=89637
SiteCode=20157498
SiteName=newport

ignoring nested elements when parsing xml with php

probably a simple question to answer for someone:::
xml:
<foobar>
<foo>i am a foo</foo>
<bar>i am a bar</bar>
<foo>i am a <bar>bar</bar></foo>
</foobar>
In the above, I want to display all elements that are <foo>. When the script gets to the line with the nested < bar > the result is "i am a bar" .. which isn't the result I had hoped for.
Is it not possible to print out the entire contents of that element as it is, so that i see: "i am a <bar>bar</bar>"
php:
$xml = file_get_contents('sample');
$dom = new DOMDocument;
#$dom->loadHTML($xml);
$resources= $dom->getElementsByTagName('foo');
foreach ($resources as $resource){
echo $resource->nodeValue . "\n";
}
After some trolling and trying to do what I needed with SimpleXML, I arrived at the following conclusion. My issue with SimpleXML was where the elements are. If the xml is structured, and the hierarchy is standard ... I have no problem.
If the XML is a web page for example, and the <foo> element is anywhere, SimpleXML doesn't have a good facility like getElementsByTagName to pull out the element wherever it may be....
<?php
$doc = new DOMDocument();
$doc->load('sample');
$element_name = 'foo';
if ($doc->getElementsByTagName($element_name)->length > 0) {
$resources = $doc->getElementsByTagName($element_name);
foreach ($resources as $resource) {
$id = null;
if (!$resource->hasAttribute('id')) {
$resource->setAttribute('id', gen_uuid());
}
$innerHTML = null;
$children = $resource->childNodes;
foreach ($children as $child) {
$tmp_doc = new DOMDocument();
$tmp_doc->appendChild($tmp_doc->importNode($child,true));
$innerHTML .= rtrim($tmp_doc->saveHTML());
}
$resource->nodevalue = $innerHTML;
}
}
echo $doc->saveHTML();
?>
Rather than writing all that code, you might try XPath. That expression would be "//foo", which would get a list of all the elements in the document named "foo".
http://php.net/manual/en/simplexmlelement.xpath.php

Parsing XML with PHP's simpleXML

I'm learning how to parse XML with PHP's simple XML. My code is:
<?php
$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\"> <iTunes> myApp </iTunes> </Document>";
$xml = new SimpleXMLElement($xmlSource);
$results = $xml->xpath("/Document/iTunes");
foreach ($results as $result){
echo $result.PHP_EOL;
}
print_r($result);
?>
When this runs it returns a blank screen, with no errors. If I remove all the attributes from the Document tag, it returns :
myApp SimpleXMLElement Object ( [0] => myApp )
Which is the expected result.
What am I doing wrong? Note that I don't have control over the XML source, since it's coming from Apple.
Your xml contains a default namespace. In order to get your xpath query to work you need to register this namespace, and use the namespace prefix on every xpath element you are querying (as long as these elements all fall under the same namespace, which they do in your example):
$xml = new SimpleXMLElement( $xmlSource );
// register the namespace with some prefix, in this case 'a'
$xml->registerXPathNamespace( 'a', 'http://www.apple.com/itms/' );
// then use this prefix 'a:' for every node you are querying
$results = $xml->xpath( '/a:Document/a:iTunes' );
foreach( $results as $result )
{
echo $result . PHP_EOL;
}
For the part about the default namespace, read fireeyedboy's answer. As mentionned, you need to register a namespace if you want to use XPath on nodes that are in the default namespace.
However, if you don't use xpath(), SimpleXML has its own magic that selects the default namespace automagically.
$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\"> <iTunes> myApp </iTunes> </Document>";
$Document = new SimpleXMLElement($xmlSource);
foreach ($Document->iTunes as $iTunes)
{
echo $iTunes, PHP_EOL;
}
this is general example
foreach ($library->children() as $child)
{
echo $child->getName() . ":\n";
foreach ($child->attributes() as $attr)
{
echo $attr->getName() . ': ' . $attr . "\n";
}
foreach ($child->children() as $subchild)
{
echo $subchild->getName() . ': ' . $subchild . "\n";
}
echo "\n";
}
for more information check this :
http://www.yasha.co/XML/how-to-parse-xml-with-php-simplexml-DOM-Xpath/article-1.html
This line:
print_r($result);
is outside the foreach loop. Maybe you should try
print_r($results);
instead.
Seems if you use the wildcard (//) on xpath it will work. Also, not sure why but if you remove the namespace attribute (xmlns) from the Document element, your current code will work. Maybe because a prefix isn't defined? Anyway, following should work:
$results = $xml->xpath("//iTunes");
foreach ($results as $result){
echo $result.PHP_EOL;
}

Extracting XML with PHP

I know how to use simplexml_load_file to get XML results if the XML format is
<bowlcontents>
<banana>yellow</banana>
<apple>red</apple>
</bowlcontents>
However, I have some code that is in the format
<bowlcontents>
<fruit type="banana" skin="yellow" />
<fruit type="apple" skin="red" />
</bowlcontents>
and I want to manipulate it in the same way as in the first example. How would I do this?
EDIT: This is precisely what I want to do, yet the code below doesn't work.
<?php
$url = "http://worldsfirstfruitAPI.com/fruit.xml";
$xml = (simplexml_load_file($url));
$results = array();
foreach ($xml->bowlcontents->fruit as $fruit) {
$results[] = array(
$fruit['type'] => $fruit['skin'],
);
}
return $results;
}
?>
So at the end of it I would like to have an array, key=value:
banana=yellow
apple=red
...
I hope this clarifies. Thanks!
As per PHP's manual, attributes are accessed using the array notation:
$bowlcontents->fruit['type'];
Come to think of it, you didn't say in your question what was your problem. If that's about iterating over nodes, you can do it using foreach.
/*
$bowlcontents = simplexml_load_string(
'<bowlcontents>
<fruit type="banana" skin="yellow" />
<fruit type="apple" skin="red" />
</bowlcontents>'
);
*/
$url = "http://worldsfirstfruitAPI.com/fruit.xml";
$bowlcontents = simplexml_load_file($url);
foreach ($bowlcontents->fruit as $fruit)
{
echo $fruit['type'], "'s skin is ", $fruit['skin'], "<br/>\n";
}

Categories