Hello I have a problem when I am trying to parse an XML file
I am trying to display only one song content using id for example
mysongs.php?id=0
It's supposed to show "I left my heart on Europa" song
and if mysongs.php?id=1
It's supposed to show "Oh Ganymede" song
I want use ID instead of the songs numbers
My problem is when I am using [$id] instead of the number [0] didn't work
echo $mysongs->song[$id]->title;
Please how can I fix my problem
This is my XML file content songs.xml
<album>
<song dateplayed="2011-07-24 19:40:26">
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
</album>
My PHP Code below
<?php
$id = $_GET['id'];
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->title;
?>
It's probably a type issue.
Try to echo the type of your id, unless you parse it somewhere it will be a string:
<?php
$id = $_GET['id'];
echo gettype($id);
Then, when you do $mysongs->song[$id], it's not an equivalent of $mysongs->song[0] but of $mysongs->song['0'] which is not the same index.
So, to have the expected output, you should cast it to int before using it as an index. For that, you can use either a cast ($id = (int) $_GET['id'];) or if it is not available in your PHP version intval ($id = intval($_GET['id']);
Then the final result would look like to...
<?php
$id = (int) $_GET['id'];
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[$id]->title;
You will need to set id as part of the column parameter within the xml files
Try code below
<album>
<song dateplayed="2011-07-24 19:40:26">
<id>1</id>
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<id>2</id>
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
</album>
You can obtain the result using two method below
1.) Using Direct Elements Method
The following example gets the node value of the and element in the first and second elements in the ".xml" file:
<?php
$id = $_GET['id'];
$mysongs = simplexml_load_file('songs.xml')or die("Error: Cannot create object");
//get the first record
echo $mysongs->song[0]->id;
echo $mysongs->song[0]->title;
//get the second record
echo $mysongs->song[1]->id;
echo $mysongs->song[1]->title;
?>
2.) using Element looping method
<?php
$mysongs=simplexml_load_file("songs.xml") or die("Error: Cannot create object");
foreach($mysongs->children() as $song_album) {
echo $song_album->id . ", ";
echo $song_album->title . ", ";
echo $song_album->artist . "<br>";
}
?>
Related
<Address FormattedInd="true">
<CityName>Athens Center</CityName>
<County>'.$Country.'</County>
<CountryName Code="GR" />
</Address>
For County I can use as <County>'.$Country.'</County>. where $Country="CountryName"
But for single tag like CountryName Code="GR" How can I pass the code "GR" as a PHP Variable.
Here, <CountryName Code="GR" /> I need the "GR" to be passed from a variable say $Code = "GR";
TIA
You can do it in a function;
function GenerateXML($tagname, $value)
{
return "
<{$tagname}>
{$value}
</{$tagname}>
";
}
Or alternatively, in a PHP file
<?
print "<tagname>{$value}</tagname>";
?>
Either way is valid
Self closing tags;
function XMLSelfClose($tagname, $valuename, $value)
{
return "<{$tagname} {$valuename}='{$value}' />";
}
print "<{$tagname} {$valuename}='{$value}' />";
You would be better off using SimpleXML than using strings to create your XML, you can easily mess up the content if you start to build the data as you are.
Your above content can be created using...
$Country = "Greece";
$Code = "GR";
// Create base document
$xml =new SimpleXMLElement('<Address FormattedInd="true"></Address>');
// Add in the CityName elment
$xml->addChild("CityName", "Athens Center");
$xml->addChild("Country", $Country);
$countryName = $xml->addChild("CountryName");
// With the CountryName element just created, add the Code attribute
$countryName->addAttribute("Code", $Code);
echo $xml->asXML();
Which outputs...
<?xml version="1.0"?>
<Address FormattedInd="true"><CityName>Athens Center</CityName><Country>Greece</Country><CountryName Code="GR"/></Address>
I had some trouble wording the question, but I think I can explain it better once I show the code:
This is my xml file (test.xml)
<?xml version="1.0" encoding="utf-8"?>
<root>
<entry id="1">
<post>05/12/2014 12:00:00</post>
<page>1</page>
<part>1</part>
<body>BODY TEXT 1</body>
</entry>
<entry id="2">
<post>05/14/2014 12:00:00</post>
<part>1</part>
<page>2</page>
<body>BODY TEXT 2</body>
</entry>
</root>
This is my PHP code (call.php)
<?php
if(isset($_GET['p']))
{
$p=$_GET['p'];
echo $p . "<br>";
$xml=simplexml_load_file("test.xml");
$day=$xml->entry[$p]->post;//<-----------PROBLEM AREA
$post=strtotime("$day");
echo $post . "<br>";
echo time() . "<br>";
if(time() >= $post)
{
echo $xml->entry[$_GET['p']]->page . "<br>";
echo $xml->entry[$_GET['p']]->part . "<br>";
}
}else{
echo "<p>Main Page Stuff</p>";
}
?>
The problem I am having is with the $day variable. If I replace [$p] with [1] or [0], it runs perfectly, but I need to have it called with a variable so I can change what part of the XML file is loaded depending on the query string, currently '?p=1'.
The echo $p results prints out 1 or 0 depending on what I put into the URL, so the $_GET is working properly, but if I put either $p or $_GET into entry[] it gives the error
Notice: Trying to get property of non-object in C:\wamp\www\xmltest\call.php on line 20
(line 20 is the one marked 'PROBLEM AREA')
is there any way to fix this problem so I can call either the first or the second depending on the query string?
I could not find a way to make the solution I was hoping for work, so I worked around it by making a new xml file for each entry instead of having each entry in one xml file.
Code used to load the xml file:
p="docs/".$_GET['p'].".xml";
if(file_exists($p))
{
$xml=simplexml_load_file($p);
$day=$xml->entry->post;
$value = $xml->entry->body;
echo "Part ".$xml->entry->part;
echo "Page ".$xml->entry->page;
}
I feel like I'm going crazy. I need to take a string of text from an xml file, and define it as a PHP variable and output it into an HTML page. I can't figure out why this wont work. Any ideas??
I have this xml document (people.xml):
<?xml version="1.0"?>
<datas>
<person>
<people>
<owner>Joe Blow</owner>
</people>
</person>
</datas>
This PHP (db.php):
<?php
$xml = simplexml_load_file('people.xml')
or die("Error: Can't load people");
$xml->person->people->owner = $owner;
?>
This HTML(index.php):
<?php include 'db.php';?>
<label for="owner-1"><?php echo $owner ?></label>
Assuming everything else is right / Based on the code you have shown,
$xml->person->people->owner = $owner;
should be
$owner = $xml->person->people->owner;
You are trying to assign the value of $owner to $xml->person->people->owner
It should be the other way round.
XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<lessons>
<lesson level="1" course="2">
<name type="Dog" category="Animals">Dog name</name>
</lesson>
</lessons>
I want to get the values saved like this:
$type = "Dog";
$category = "Animals";
$name = "dog name";
This is what I've done:
foreach($xml->name as $name){
$type = $name['type'];
$category = $name['category'];
echo "Type: $type Category: $category<br>";
// AND TO get the text, haven't figuered it out yet.. <name ..="" ..="">text</name>
}
But it doesn't work. Don't get any errors neither any output. Any ideas?
EDIT:
OK. I changed foreach($xml->name as $name)
to foreach($xml->lesson->name as $name)
so I get the values of the attribute. But now I don't know how to get the value of the children.
I've tried this: $xml->lesson->children()
It prints children()
SOLVED: $text = $xml->lesson->children();
echo $text;
PROBLEM WAS: I'm using utf-8 in my other code but didn't change it.
Edit : this part related to a question typo. If you copied your xml directly from where you were editting it, then part of the problem might be that it is malformed. You have an opening <lessons> but you appear to wrongly try to close it with </lesson>.
Also, depending on your root node settings, ->name may or may not be a child of the $xml object. Can you post a var_dump() of it and get some clues?
I think, there is some problem in your xml.
-> You have to close lessons tag correctly.Because you have entered </lesson> (see last line) instead of </lessons>. If you start any tag, you should use the same tag name while closing..
you can use this code to extract values from your xml,
<?php
$xmlstring='<lessons>
<lesson level="1" course="2">
<name type="Dog" category="Animals">Dog name</name>
</lesson>
</lessons>';
$xml = simplexml_load_string($xmlstring);
$ATTRIBUTE=array();
$counter = 0;
foreach($xml->children() as $key=>$child)
{
$counter++;
$ATTRIBUTE[$counter]["type"]=$child->name->attributes()->type;
$ATTRIBUTE[$counter]["category"]=$child->name->attributes()->category;
$ATTRIBUTE[$counter]["value"]= $child->name;
}
echo "<pre>";
print_r($ATTRIBUTE);
?>
here you will get everything in array. So you can fetch based on your requirement.
Hi Im trying to parse an xml feed using simplexml in php.
The xml feed is laid out as follows:
<Member>
<MemberType>Full</MemberType>
<JoinDate>2010-06-12</JoinDate>
<DataType>A</DataType>
<Data>
<FirstName>Ted</FirstName>
<LasttName>Smith</LasttName>
<Data1>56</Data1>
<Data2>100</Data2>
<Data3>120</Data3>
</Data>
</Member>
<Member>
<MemberType>Full</MemberType>
<JoinDate>2010-06-12</JoinDate>
<DataType>B</DataType>
<Data>
<FirstName>Ted</FirstName>
<LasttName>Smith</LasttName>
<Data1>57</Data1>
<Data2>110</Data2>
<Data3>130</Data3>
</Data>
</Member>
<Member>
<MemberType>Full</MemberType>
<JoinDate>2010-06-12</JoinDate>
<DataType>C</DataType>
<Data>
<FirstName>Ted</FirstName>
<LasttName>Smith</LasttName>
<Data4>58</Data4>
<Data5>115</Data5>
<Data6>230</Data6>
</Data>
</Member>
where the member element loops over and over again in the xml doc, but the data inside it changes. What im trying to do is enter all the data for certain members into an sql database. So ideally i want to enter this all in one line in the db. The xml feed contains different member types, like 'full' or 'associate'.
At the moment i am trying to loop through all the full members, and get all the data for this particular member. The data for each member is broken up into three parts each with a separate member tag, so above Ted Bloggs has data in three member tags, where Datatype is A, B and C
$PLF = simplexml_load_file('../XML/Members.xml');
foreach ($PLF->Root->xpath('//Member') as $member) {
if ($member->MemberType == 'Full') {
echo $member->MemberType.'<br/>';
echo $member->JoinDate.'<br />';
echo $member->DataType.'<br/>';
echo $member->Data->FirstName.'<br/>';
echo $member->Data->LastName.'<br/>';
echo $member->Data->Data1.'<br/>';
echo $member->Data->Data2.'<br/>';
echo '<br />';
}}
the code i have at the moment can only pull data from the first type (type A) in each loop, and i really want to combine all types A, B, and C into the same loop. So i can get all the data for each member like Ted Smith into one line in the DB.
I use simple xml to read some remote files and loop thru them as well. This is my code:
$sUrl = "some url";
$sContent = file_get_contents($sUrl);
$oXml = new SimpleXMLElement($sContent);
$aReturn = array();
foreach ($oXml->children() as $oStation)
{
$iRackId = (int)$oStation->rack_id;
$dLong = (double)str_replace(",", ".", $oStation->longitute);
$dLati = (double)str_replace(",", ".", $oStation->latitude);
$sDescription = (string)$oStation->description;
$aRes = array();
$aRes['rack_id'] = $iRackId;
$aRes['longitute'] = $dLong;
$aRes['latitude'] = $dLati;
$aRes['description'] = utf8_decode($sDescription);
if ($dLong > 0 && $dLati > 0)
$aReturn[$iRackId] = $aRes;
}
What I do is I put the result of the XML file into an array. Later in the code I save that data to the database as well.
Hope this helped you. I don't use xpath... had nothing but problems with it and didn't had the time to sort them out. This seems to work for me though.
Br,
Paul Peelen