How to index XML elements in PHP? - php

I am dummy to PHP and XML, so please be patient if my question seems dumb.
I want to know how to index the XML elements so that I can access them. I am planning to put them into an array. However, I don't know how to get the number of elements returned.
Here are the codes:
exer.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<actionstars>
<name>Jean Claude Van Damme</name>
<name>Scott Adkins</name>
<name>Michael Jai White</name>
<name>Dolph Lundgren</name>
<name>Tom Cruise</name>
<name>Michael Worth</name>
</actionstars>
index.php
<?php
$dom = new DomDocument();
$dom->load("exer.xml");
$names = $dom->getElementsByTagName("name");
echo count($names);
foreach($names as $name) {
print $name->textContent . "<br />";
}
?>
When I do the echo count($names); it returns 1, which is obviously not the number of elements. Please help.

Have a look at the return value of getElementsByTagName, which will be a DOMNodeList.
Also for your problem you could do something like:
$names = array();
foreach ($dom->getElementsByTagName("name") as $nameNode) {
$names[] = $nameNode->nodeValue;
}
You don't have to actually check the return value of getElementsByTagName, for it will allways be a DOMNodeList. This way you can use it directly in the foreach-loop whithout assigning unneeded variables.
What you have to check, is the size of $names, after the loop.

Related

php echo DOM Elements as strings

I have used the following code to store a small timetable in an array. I am trying to return specific elements of the array but get the error Cannot use object of type DOMElement as array.
I would be grateful if somebody could tell me how to retrieve the nodeValue of certain elements and display them.
$doc = new DOMDocument();
$doc->loadHTML($timetable);
$headers = $doc->getElementsByTagName('th');//' missed which is typo i think
$cells = $doc->getElementsByTagName('td');//' missed which is typo i think
$array = iterator_to_array($cells);
I can loop through this and display the entire table with a for loop, and that's fine, but I can't return 1 value from the array:
for ($i=0; $i<=5; $i++){
$val = $array[$i];
echo $val[1]->nodeValue;
}
And this returns the error I mentioned above.

count of array elements in php

I m trying to display no of elements in an array,but its showing 1 when i m trying to print the count
<?php
if(!$xml=simplexml_load_file('sunglasses.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}
$array1=array();
foreach($xml as $syn)
{
for($i=0;$i<count($syn->productId);$i++)
{
$array1=$syn->productId;
}
}
echo count($array1, COUNT_RECURSIVE);
?>
There are 10 products in the xml file.So i want the count to be 10,but its printing only 1.
Please tell me whats wrong in the code.
Your formatting of code is horrible.
And yes, there might be 10 elements in the xml, but there is only one in $array1 because only the last assignment is present. You never told to $array1 to push values into the array, despite the fact you declared it as array. Assignation process = does not push values, if explicitly not called via array_push() or [] syntax.
$array1[] = $syn->productId;
Should work.
You should have tested the result at least. var_dump()'ing the $array1 will give you result of only one value - the last value, and you would be able to understand that something is wrong.
Following Change in code will resolved your issue.
<?php
if(!$xml=simplexml_load_file('sunglasses.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}
$array1=array();
foreach($xml as $syn)
{
for($i=0;$i<count($syn->productId);$i++)
{
// here need to add the result in array. not to assign value directly to array object.
$array1[] = $syn->productId;
}
}
echo count($array1, COUNT_RECURSIVE);
?>

PHP Echo XML Attributes Without Repeating

my question has to do with PHP and XML. I would like to echo out some attributes, but echo ones that repeat only once.
Say this was the XML I was dealing with, and it was called beatles.xml:
<XML_DATA item=“TheBeatles”>
<Beatles>
<Beatle Firstname=“George” Lastname=“Harrison” Instrument=“Guitar”>Harrison, George</Beatle>
<Beatle Firstname=“John” Lastname=“Lennon” Instrument=“Guitar”>Lennon, John</Beatle>
<Beatle Firstname=“Paul” Lastname=“McCartney” Instrument=“Bass”>McCartney, Paul</Beatle>
<Beatle Firstname=“Ringo” Lastname=“Starr” Instrument=“Drums”>Starr, Ringo</Beatle>
</Beatles>
</XML_DATA>
This is the PHP I have so far:
$xml = simplexml_load_file("http://www.example.com/beatles.xml");
$beatles = $xml->Beatles->Beatle;
foreach($beatles as $beatle) {
echo $beatle->attributes()->Instrument.',';
}
I would expect this to echo out Guitar,Guitar,Bass,Drums, but I would like Guitar to only display once. How would I prevent repeat attribute values from echoing out?
Inside the foreach loop, cast the instrument name as a string and push it into an array. Once the loop finishes execution, you will have an array containing all the instrument names (with duplicates, of course). You can now use array_unique() to filter out the duplicate values from the array:
$instruments = array();
foreach($beatles as $beatle) {
$instruments[] = (string) $beatle->attributes()->Instrument;
}
$instruments = array_unique($instruments);
Demo.
$xml = simplexml_load_file("http://www.example.com/beatles.xml");
$beatles = $xml->Beatles->Beatle;
$result = array();
foreach($beatles as $beatle) {
if (!array_key_exists($beatle->attributes()->Instrument, $result)) {
$result[] = $beatle->attributes()->Instrument;
// echo $beatle->attributes()->Instrument.',';
}
}
then Loop through the $result array with foreach
Either use xpath.

Converting XML file elements into a PHP array

I'm trying to convert a Steam group members list XML file into an array by using Php.
The XML file is: http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml
The elements are the member's steam IDs, such as 76561198000264284
How can I go about doing this?
Edit: So far I've used something like this:
$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);
It outputs the first few elements, not ones specifically
from
This should return the fully accessible array:
$get = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($get);
print_r($arr);
You can now access items like this:
echo $arr->groupID64;
echo $arr->members->steamID64;
Edit:
To parse the streamID, you can do a for loop
$ids = $arr->members->steamID64;
foreach($ids as $id) {
echo $id;
}
you can use below functional code to get your correct answer
<?php
$getfile = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($getfile);
foreach($arr->members->steamID64 as $a => $b) {
echo "<br>".$a,'="',$b,"\"\n";
}
?>
OUTPUT
steamID64="76561198009904532"
steamID64="76561198004808757"
steamID64="76561198000264284"
steamID64="76561198016710420"
steamID64="76561198005429187"
steamID64="76561198030184436"
steamID64="76561197980763372"
steamID64="76561197972363016"
steamID64="76561198045469666"
steamID64="76561198010892015"
steamID64="76561198028438913"
steamID64="76561197967117636"
steamID64="76561197980283206"
steamID64="76561197992198727"
steamID64="76561198018960482"
steamID64="76561198071675315"
steamID64="76561198010447988"
steamID64="76561198025628761"
if you wish to customize you can make it as per your need. let me know if i can help you more..

adding data to php array within a loop

I am parsing data from a website via xml that always changes so I do not know what data to search for, just the location. I get the data by calling upon the specific class for the data needed. Within this class that is retrieved, there are only certain things I need retrieved. So for example, I retrieve the class .candy. Now .candy corresponds to different parts on the website so let us say that candy retrieves "Cookies Chocolate gummy bear". I only want "chocolate".
My idea was to put everything into an array an array and then access it. Assume the array is called test, then I would want to access "chocolate" by $test[1];
It is not working for me (says array is out of bounds whenever I put a number bigger than 0) and I was wondering if anyone knows where my mistake is within my code? Please note that the above was purely an example for better understanding and not the actually data I need.
Thank you
function getData($html)
{
#$doc=new DOMDocument();
#$doc->loadHTML($html);
$xml=simplexml_import_dom($doc); // just to make xpath more simple
//$images=$xml->xpath('//[]');
$info=$xml->xpath('//*[#class="date"]');
$arr= array();
foreach ($info as $img) {
$arr= array($img);
}
return $arr[3];
}
You are replacing $arr in every loop. $arr[] = $img; should work.
Example:
function getData($html)
{
#$doc = new DOMDocument();
#$doc->loadHTML($html);
$xml = simplexml_import_dom($doc);
$info = $xml->xpath('//*[#class="date"]');
$arr = array();
foreach ($info as $img)
{
$arr[] = $img;
}
return $arr[3];
}
foreach ($info as $img) {
$arr[] = $img;
}

Categories