Extracting Certain XML Elements with PHP SimpleXML - php

I am having some problems parsing this piece of XML using SimpleXML. There is always only one Series element, and a variable number of Episode elements beneath. I want to parse XML so I can store the Series data in one table, and all the Episode data in another table.
XML:
<Data>
<Series>
<id>80348</id>
<Genre>|Action and Adventure|Comedy|Drama|</Genre>
<IMDB_ID>tt0934814</IMDB_ID>
<SeriesID>68724</SeriesID>
<SeriesName>Chuck</SeriesName>
<banner>graphical/80348-g.jpg</banner>
</Series>
<Episode>
<id>935481</id>
<Director>Robert Duncan McNeill</Director>
<EpisodeName>Chuck Versus the Third Dimension 2D</EpisodeName>
<EpisodeNumber>1</EpisodeNumber>
<seasonid>27984</seasonid>
<seriesid>80348</seriesid>
</Episode>
<Episode>
<id>935483</id>
<Director>Robert Duncan McNeill</Director>
<EpisodeName>Buy More #15: Employee Health</EpisodeName>
<EpisodeNumber>2</EpisodeNumber>
<seasonid>27984</seasonid>
<seriesid>80348</seriesid>
</Episode>
</Data>
When I attempt to access just the first Series element and child nodes, or iterate through the Episode elements only it does not work. I have also tried to use DOMDocument with SimpleXML, but could not get that to work at all.
PHP Code:
<?php
if(file_exists('en.xml'))
{
$data = simplexml_load_file('en.xml');
foreach($data as $series)
{
echo 'id: <br />' . $series->id;
echo 'imdb: <br />' . $series->IMDB_ID;
}
}
?>
Output:
id:80348
imdb:tt0934814
id:935481
imdb:
id:1534641
imdb:

I just discovered the stupid mistake I was making.
The PHP code should have been like this:
<?php
if(file_exists('en.xml'))
{
$data = simplexml_load_file('en.xml');
foreach($data->Series as $series)
{
echo 'id: <br />' . $series->id;
echo 'imdb: <br />' . $series->IMDB_ID;
}
}
?>
The first time I tried this (and it did not work) I was using;
$data->series as $series
So it was a capital 'S' that was the issue.

Related

How to read xml file from url with symfony [duplicate]

It looks like there are many problems with simpleXML in PHP. I'm running the latest version of php on Windows and I just can not get the basic examples of simpleXML to work as in the documentation.
My xml file is:
<?xml version="1.0" encoding="ISO-8859-1"?>
<programme>
<title>Billy Bushwaka</title>
<episodeNumber>2</episodeNumber>
<description>Billy Bushwaka entertains</description>
<url>play.swf</url>
</programme>
My PHP program is:
<?php
$xml = simplexml_load_file("local.xml");
$result = $xml->xpath("//programme");
echo "Title: " . $result . "</br>";
?>
All I get is the following:
Title: Array
How can I get "Title: Billy Bushwaka"?
There are no repeats of XML data so I do not want to use arrays.
SimpleXML 101
First of all, always name your PHP variables after the node they represent.
// the root node is <programme/>
$programme = simplexml_load_file("local.xml");
Access to children (nodes) as if they were object properties.
echo $programme->title;
If there are multiple children using the same name, you can specify their 0-based position
// first <title/> child
echo $programme->title[0];
// create or change the value of the second <title/> child
$programme->title[1] = 'Second title';
Access to attributes as if they were array keys
// <mynode attr="attribute value" />
echo $mynode['attr'];
XPath always returns an array.
Back to your case, the best way to access that <title /> node would be
$programme = simplexml_load_file("local.xml");
echo "Title: " . $programme->title;
First of all, simplexml xpath method always returns an array of matches. Even if there is only 1 match (or even 0, in which case result is an empty array). This is why you get "Array" in the output.
Secondly, if you want just the title, then you need to change your xpath query:
$result = $xml->xpath("//programme/title");
echo "Title: " . $result[0] . "</br>";
You should probably change the xpath to //programme/title and then echo $result[0] or leave the xpath as it is and echo $result[0]->title. Remember var_dump will always help you.
I think you want:
$result = $xml->xpath("/programme/title");
echo "Title: " . $result[0] . "</br>";
$xml = simplexml_load_file("local.xml");
echo $xml->programme->title;
......
echo $xml->programme->description;

handle multiple xml tags in one document with php

i today tried to export a big xml file with php to add the content later to a mysql database.
i got in contact with PHP SimpleXML today and it worked great for just one big plot of a xml tag, but when i add more like:
<features>
<name>Holy moly</name>
....
</features>
<features>
<name>what the...</name>
...
</features>
my script cant handle more than one big xml "all over" tag.
heres my php parse script:
<?php
include 'example.php';//heres my xml content
$features = new SimpleXMLElement($xmlstr);
/* For each <character> node, we echo a separate <name>. */
foreach ($features->properties as $properties) {
echo "<br />".$properties->name, ' played by ', $properties->website, PHP_EOL;
}
?>
thank you for your help
A well-formed XML document should have only one root element, encapsulating all other elements. So, I would suggest that you encapsulate the features element with a higher root element.
Solution:
foreach ($root->features as $features) {
foreach ($features->properties as $properties) {
echo "<br />".$properties->name, ' played by ', $properties->website, PHP_EOL;
} }

How can I extract data from XML to PHP using SimpleXML and echo?

I've successfully integrated the LinkedIn API with my website, but I'm struggling to extract information from the XML. At the moment I'm just trying to print it out so I can proceed to use the user's information once they have logged in and given permission.
Below is the format of the XML, and further down is the code I am using to extract the information. The "first name", "last name" and "headline" calls work perfectly, but where an element has sub-headings, nothing is printed out. I've tried using
echo 'Positions: ' . $xml->{'positions:(title)'};
but it doesn't work.
Here is the XML:
<person>
<id>
<first-name />
<last-name />
<headline>
<location>
<name>
<country>
<code>
</country>
</location>
<industry>
<summary/>
<positions total="">
<position>
<id>
<title>
<summary>
<start-date>
<year>
<month>
</start-date>
<is-current>
<company>
<name>
</company>
</position>
</person>
This is the code I've been using to try to extract the information. I know I have to include the sub-heading somehow but I just don't know how!
echo 'First Name: ' . $xml->{'first-name'};
echo '<br/>';
echo 'Last Name: ' . $xml->{'last-name'};
echo '<br/>';
echo 'Headline: ' . $xml->{'headline'};
echo '<br/>';
echo 'Positions: ' . $xml->{'positions'};
Any help would be greatly appreciated, thanks for reading!
Using SimpleXML, you'd access the LinkedIn XML data properties as follows:
Anything with a dash in the property gets {}, so first-name becomes:
$xml->{'first-name'}
Anything without a dash such as headline, is referenced like:
$xml->headline
Anything that is a collection, such as positions, is referenced like:
foreach($xml-positions as $position) {
echo $position->title;
echo $position->{'is-current'};
}
Your XML is not valid, its not well formed. Anyway here's a sample XML and how to use it.
$v = <<<ABC
<vitrine>
<canal>Hotwords</canal>
<product id="0">
<descricao>MP3 Apple iPod Class...</descricao>
<loja>ApetreXo.com</loja>
<preco>à vista R$765,22</preco>
<urlImagem>http://im</urlImagem>
<urlProduto>http://</urlProduto>
</product>
</vitrine>
ABC;
$xml = simplexml_load_string($v);
foreach ($xml->product as $c){
echo $c->loja; //echoing out value of 'loja'
}
Try to use PHP's XML Parser instead:
http://www.php.net/manual/en/function.xml-parse.php
Tried Paul's answer above for:
foreach($xml-positions as $position) {
echo $position->title;
echo $position->{'is-current'};
}
didn't work for me - so I used this - not as elegant but works
for($position_num = 0; $position_num < 10;$position_num++){
echo $xml->positions->position[$position_num]->company->name;
}
Your XML is not well-formed... there are several elements without close tags. So we have no way to know for sure the structure of your XML. (You can't do that in XML like you can in HTML.)
That being said, assuming that <person> is the context node, you can probably get the content of the <title> element using an XPath expression, as in
$xml->xpath('positions/position/title');
I'm assuming $xml is a SimpleXMLElement object.

how to get the values from this xml using dom in php?

how can i get the values of a,b and c from the following xml code?
<result name="response" f="139" c="0">
−
<doc score="5.06756" pos="0">
<snippet name="a" highlighted="yes">example</snippet>
<snippet name="b" highlighted="yes">bexample</snippet>
<snippet name="c">cexample</snippet>
</doc>
</result>
I tried to print the nodes, but It failed:
$xmlDoc = new DOMDocument();
$xmlDoc->load($content);
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br />";
}
Can anyone tell me how I can parse it? I cannot use simple xml, so I am moving to Dom.
Using DOM allows you to use several distinct ways of extracting informations.
For example, you could work with :
DOMDocument::getElementsByTagName, to extract all tags having a specific name.
Or DOMXPath, for more complex queries.
As an example, here's a portion of code that demonstrates how to use the first solution to extract all <snippet> tags :
$snippets = $xmlDoc->getElementsByTagName('snippet');
foreach ($snippets as $tag) {
echo $tag->getAttribute('name') . ' = ' . $tag->nodeValue . '<br />';
}
And you'd get this output :
a = example
b = bexample
c = cexample
And, as another example, here's a solution that demonstrates how to use the second solution, to do a more complex query on the XML data -- here, extracting the <snippet> tag that as it's name attribute with a value of a :
$xpath = new DOMXPath($xmlDoc);
$snippetsA = $xpath->query('//snippet[#name="a"]');
if ($snippetsA->length > 0) {
foreach ($snippetsA as $tag) {
echo $tag->getAttribute('name') . ' = ' . $tag->nodeValue . '<br />';
}
}
Which only gets you one result -- the corresponding tag :
a = example
Starting from here, the possibilities are almost limitless ;-)

Basic simpleXML working example?

It looks like there are many problems with simpleXML in PHP. I'm running the latest version of php on Windows and I just can not get the basic examples of simpleXML to work as in the documentation.
My xml file is:
<?xml version="1.0" encoding="ISO-8859-1"?>
<programme>
<title>Billy Bushwaka</title>
<episodeNumber>2</episodeNumber>
<description>Billy Bushwaka entertains</description>
<url>play.swf</url>
</programme>
My PHP program is:
<?php
$xml = simplexml_load_file("local.xml");
$result = $xml->xpath("//programme");
echo "Title: " . $result . "</br>";
?>
All I get is the following:
Title: Array
How can I get "Title: Billy Bushwaka"?
There are no repeats of XML data so I do not want to use arrays.
SimpleXML 101
First of all, always name your PHP variables after the node they represent.
// the root node is <programme/>
$programme = simplexml_load_file("local.xml");
Access to children (nodes) as if they were object properties.
echo $programme->title;
If there are multiple children using the same name, you can specify their 0-based position
// first <title/> child
echo $programme->title[0];
// create or change the value of the second <title/> child
$programme->title[1] = 'Second title';
Access to attributes as if they were array keys
// <mynode attr="attribute value" />
echo $mynode['attr'];
XPath always returns an array.
Back to your case, the best way to access that <title /> node would be
$programme = simplexml_load_file("local.xml");
echo "Title: " . $programme->title;
First of all, simplexml xpath method always returns an array of matches. Even if there is only 1 match (or even 0, in which case result is an empty array). This is why you get "Array" in the output.
Secondly, if you want just the title, then you need to change your xpath query:
$result = $xml->xpath("//programme/title");
echo "Title: " . $result[0] . "</br>";
You should probably change the xpath to //programme/title and then echo $result[0] or leave the xpath as it is and echo $result[0]->title. Remember var_dump will always help you.
I think you want:
$result = $xml->xpath("/programme/title");
echo "Title: " . $result[0] . "</br>";
$xml = simplexml_load_file("local.xml");
echo $xml->programme->title;
......
echo $xml->programme->description;

Categories