Extract specific XML node - php

I have the following XML file:
<XmlSports xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" CreateDate="2014-11-17T14:46:38.6954+01:00">
<Sport Name="SOCCER" ID="7">
<Event Name="African Nations Cup" ID="54" IsLive="false">
<Match Name="DR Congo v Sierra Leone" ID="1552163" StartDate="2014-11-19T15:00:00.1+01:00">
<Bet Name="Double Chance" ID="6337125"/>
<Bet Name="Draw No Bet" ID="6337124"/>
<Bet Name="Match Odds" ID="6337119"/>
<Bet Name="Odds or Evens" ID="6337123"/>
<Bet Name="Over/Under" ID="6337121"/>
</Match>
</Event>
</Sport>
I am just including a small portion of the file but basically this file includes other sports aside from just soccer, separated by 'Sport Name="NAME OF SPORT" ID="ID OF SPORT"'.
I want to extract just the SOCCER node. I have tried using XPath but have not succeeded.
How can I extract just the 'Sport Name="SOCCER" ID="7"' part out of this XML?

This should give you a starting point.
Assuming that $string contains your valid xml.
$xml = simplexml_load_string($string);
$sport = $xml->xpath("//Sport[#Name='SOCCER']");
print_r($sport);

I wish you have tried this one
//XmlSports/Sport[#Name='SOCCER' and #ID='7']

Related

How to get specific tag in KML file using php DOMDocument?

I have a .kml file shaped like this :
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<name>myFile.shp</name>
<Style id="style1">
<PolyStyle>
<color>ff00ff00</color>
</PolyStyle>
</Style>
<Folder id="layer 0">
<name>background</name>
<Placemark>
<styleUrl>#style1</styleUrl>
<LineString>
<coordinates>
-2.94040373,54.83409343483 -2.943834733,54.893839393
</coordinates>
</LineString>
</Placemark>
</Folder>
</Document>
</kml>
Question
How can I get this file as a DOMDocument, and get ALL tag element with name "coordinates" ?
The goal is to be able to get the coordinates, even if the file shape change, like for example :
<kml xmlns="http://earth.google.com/kml/2.0">
<Folder>
<name>OpenLayers export</name>
<description>No description available</description>
<Placemark>
<name>OpenLayers.Feature.Vector_7341</name>
<description>No description available</description>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-2.94040373,54.83409343483 -2.943834733,54.893839393
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
</kml>
My attempts was to loop through the document using simplexml_load_file() but unfortunately I would not be reliable as the "tag order" change between those 2 documents, and I do not know why it does not follow a single pattern (which lead me to ask this question because it may have more than 2 shape for a KML ? correct me if I am wrong).
Use DOMDocument class to parse XML. Then use getElementsByTagName() to get all coordinates elements.
$dom = new DOMDocument();
// load file
$dom->load("file.kml");
// get coordinates tag
$coordinates = $dom->getElementsByTagName("coordinates");
foreach($coordinates as $coordinate){
echo $coordinate->nodeValue;
}

Search for and replace values in a KML file

I'm very new to php so go easy on me.
I'm trying to search through a KML file for latitude and longitude values, then replace them with user inputted lat/long values. The problem I'm having is actually searching through the KML file to find the specific lat/long values to be replaced.
KML:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Folder>
<name>Folder-Name</name>
<open>1</open>
<gx:Tour>
<name class="name">Tour-Name</name>
<gx:Playlist>
<gx:FlyTo>
<LookAt>
<gx:horizFov>100</gx:horizFov>
<longitude class="lookat-long">33.33333</longitude>
<latitude class="lookat-lat">-111.11111</latitude>
<altitude>0</altitude>
<heading>0</heading>
<tilt>60</tilt>
<range>100</range>
<altitudeMode>relativeToGround</altitudeMode>
</LookAt>
</gx:FlyTo>
</gx:Playlist>
</gx:Tour>
</Folder>
</kml>
I need to replace "33.33333" and "-111.11111" with user inputted values. I have tried using SimpleXML, but it does not recognize the gx: part of the tag, since that is KML specific, and not part of XML. So when I try this code:
<?php
$xml = simplexml_load_file('my_kml_file');
print_r($xml)
?>
I get this output:
SimpleXMLElement Object ( [Folder] => SimpleXMLElement Object ( [name] => Temporary Places [open] => 0 ) )
It just stops at <open> because it doesn't recognize the rest. I have spent hours upon hours trying to figure out how to best do this and I just can't. Please help.
You can use the xpath method to get the namespaced node like so:
$xml = simplexml_load_file('my_kml_file');
$xml->xpath('//gx:Tour/gx:Playlist/gx:FlyTo')[0]->LookAt->longitude = 'newValue';
$xml->xpath('//gx:Tour/gx:Playlist/gx:FlyTo')[0]->LookAt->latitude = 'newValue';
print_r($xml->asXml());
Output:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Folder>
<name>Folder-Name</name>
<open>1</open>
<gx:Tour>
<name class="name">Tour-Name</name>
<gx:Playlist>
<gx:FlyTo>
<LookAt>
<gx:horizFov>100</gx:horizFov>
<longitude class="lookat-long">newValue</longitude>
<latitude class="lookat-lat">newValue</latitude>
<altitude>0</altitude>
<heading>0</heading>
<tilt>60</tilt>
<range>100</range>
<altitudeMode>relativeToGround</altitudeMode>
</LookAt>
</gx:FlyTo>
</gx:Playlist>
</gx:Tour>
</Folder>
</kml>

Strip all tags from an XML file

I have a large XML file I would like to strip all the tags and leave node values only. I want each node value in a separate line. How can I do that?
Can I use a free software to do it or use a PHP or ASP.NET Code. I looked at XSLT option also. It is probably too much for RegEX. I explored PHP options looked at simplexml_load_file(), strip_tags(), get_file_contents() but failed.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- a comment -->
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<address>
<city>Melbourne </city>
<zip>01803 </zip>
</address>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>
Edit: This is what I tried, among other things.
<?php
$xml = simplexml_load_file('myxml.xml');
echo strip_tags($xml);
?>
This should do ya:
<?php
$xml = file_get_contents('myxml.xml');
$xml = nl2br($xml);
echo strip_tags($xml,"<br>");
?>
The reason you were missing line breaks was because in XML, it is stored as plaintext linebreaks \n whereas when displaying as HTML you must have explicit <br> linebreaks. Because of this the good PHP folks made a handy function called nl2br() to do this for you.
Here is a short and simple XSLT solution:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="text()">
<br /><xsl:value-of select="concat(.,'
')"/>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided XML document (would work on any XML document):
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<address>
<city>Melbourne </city>
<zip>01803 </zip>
</address>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>
the wanted result is produced:
<br/>Empire Burlesque
<br/>Bob Dylan
<br/>USA
<br/>Columbia
<br/>10.90
<br/>Melbourne
<br/>01803
<br/>1985
<br/>Hide your heart
<br/>Bonnie Tyler
<br/>UK
<br/>CBS Records
<br/>9.90
<br/>1988
and it is displayed by the browser as:
Empire Burlesque
Bob Dylan
USA
Columbia
10.90
Melbourne
01803
1985
Hide your heart
Bonnie Tyler
UK
CBS Records
9.90
1988

DomDoc/SimpleXML/XSLT: parsing to add auto-incrementing id attributes to each unique element child of an element

I have been troubleshooting this for a while, and I am kind of new to programming. Even when I find an error, it's very difficult to figure out how to correct it. Right now, I am trying to figure out how I have used xpath wrong because someone told me that I am using xpath wrong. I hope someone can give me a jump start by telling me what I am doing wrong, specifically with iterating, if I am doing anything wrong. This is my last night to work on this project, and I really want to finish it if I can. So, I could really use help. Here is the code I am using, with comments:
$xml = #simplexml_load_file("original.xml"); //Loading the original file, dubbed original.xml.
$array_key_target_parent = count($xml->xpath('/doc/*'); //Puts all of the children of <doc> into an _iterable_ array.
$key_targets = foreach($array_key_target_parent;){
foreach($array_key_target_parent as $single_target){ // I tried foreach($array_key_target_parent[$i]). It doesn't work, so don't even go there.
$current_target = current($single_target);
count($xml->xpath('/doc/$current_target/*');
}
} */ ////Puts the targets for keying into iterable arrays. =>1 makes the array start from 1, so the id's will be right.
/* At this point, we have multiple elements that we want to key, each having a unique name. There's <element_type1a> and <element_type1b>, etc. We want each one to have its own id set. So, we have to embed iteration within iteration. */
foreach($key_target){ //This will ensure that every unique element that we want to key gets its key set.
{
$id = current($key_target=>1); //This allows us to reset the id to 1 (=>1), each time the key algorithm starts for a new element.
foreach($key_target as $id){ //I tried for($i=0, $key_target[$i]; $i>$key_target; $i++), and it didn't work, so don't even go there.
addAttribute('id', '$id');
}
} //Adds an 'id' attribute and a unique number to each target.
$xml->asXML("new.xml"); //saves the output as a new xml document, new.xml
I also have a generic XML file:
<doc>
<info_type1>
<element_type1a>not_unique_data</element_type1a>
<element_type1b>unique_data</element_type1b>
<element_type2a>not_unique_data</element_type2a>
<element_type2b>not_unique_data</element_type2b>
<element_type2c lang="fr">not_unique_data</element_type2c>
<!-- ... --->
<element_typeNxM>unique_data</element_typeNxM>
</info_type1>
<info_type2>
<element_type1a>repeat_data(info_type1_element1a)</element_type1a>
<element_type2a>not_unique_data</element_type2a>
</info_type2>
<!-- ... --->
<info_typeN>
<descendants></descendants>
</info_typeN>
</doc>
Desired output:
<datatables>
<table id="element_type1">
<element_type1a id="1">unique_data</element_type1a>
<element_type1b id="2">unique_data</element_type1b>
<!-- ... --->
<element_type1N id="M">unique_data</element_type1N>
</table>
<table id="element_type2">
<element_type2a id="1">unique_data</element_type2a>
<element_type2b id="2">unique_data</element_type2b>
<!-- ... --->
<element_type2N id="M">unique_data</element_type2N>
</table>
<table id="element_type2_fr">
<element_type2a lang="fr" id="1">unique_data</element_type2a>
<element_type2b lang="fr" id="2">unique_data</element_type2>
<!-- ... (there are five languages) --->
<element_type2N lang="fr" id="M">unique_data</element_type2N>
</table>
<!-- ... --->
<table id="element_typeN">
<descendants></descendants>
</table>
</datatables>
and
<intermediary_tables>
<table id="intermediary_table_type1xtype2">
<element id="1">
<type1ID>1</type1ID>
<type2ID>1</type2ID>
</element>
<element id="2">
<type1ID>1</type1ID>
<type2ID>2</type2ID>
</element>
<element id="3">
<type1ID>2</type1ID>
<type2ID>1</type2ID>
</element>
<element id="4">
<type1ID>2</type1ID>
<type2ID>2</type2ID>
</element>
<!-- ... --->
<element id="N">
<type1ID>M</type1ID>
<type2ID>Z</type2ID>
</element_type2N>
</table>
<table id="intermediary_table_typeMxtypeN">
<descendants></descendants>
</table>
</intermediary_tables>
I have also seen many very similar questions asked, and I have some resources that I gathered from them and read:
http://www.ibm.com/developerworks/xml/library/x-xmlphp1/index.html
http://www.php.net/manual/en/simplexmlelement.addattribute.php
http://www.learn-xslt-tutorial.com/
http://msdn.microsoft.com/en-us/library/ms256103.aspx
http://php.net/manual/en/class.domdocument.php
These are the most useful links:
http://www.capcourse.com/Library/NormalizingXML/Part1.html
http://forums.tizag.com/showthread.php?t=17821
And I found that none of the applications of the questions were able to produce the result I am trying to achieve. The exception, though, is the capcourse.com link. It's geared towards a graduated CS audience, and it seems like they're doing the same thing, except the ID's they are using aren't autoincrementing. The algorithm they use is extremely complex, and they haven't commented their code at all. They're using a namespace within their namespace for some reason, and even though it's the closest I can find, I can't reproduce it in the slightest.
Update
Real-world extract from an XML document that I would like to parse to change the data structure:
<?xml version="1.0"?>
<!DOCTYPE catalog [
<!ELEMENT catalog (entry*)>
<!ELEMENT entry (ent_seq, country*, arist+, info?, title+)><!-- Entries consist of the name of the album, artist, and more information about the CD. Each entry must contain an artist and an album title. -->
<!ELEMENT ent_seq (#PCDATA)><!-- A unique numeric sequence, showing the entry number -->
<!ELEMENT title (#PCDATA)><!-- The title of the album/the album name. -->
<!ELEMENT artist (band+, name, nickname*)><!-- The name of the band, and if there was a famous artist, his name and nickname. Must contain a band element. -->
<!ELEMENT band (#PCDATA)><!-- The name of the band. -->
<!ELEMENT name (#PCDATA)><!-- The name of any famous artist in the band. -->
<!ELEMENT nickname (#PCDATA)><!-- The nickname of the popular artist that precedes the nickname element, from the band. -->
<!ELEMENT country (#PCDATA)><!-- Specifies countries where the album was released -->
<!ELEMENT company (name, country)><!-- Company/producer info. The company's name is in the name element, and the country where the company originated is in the country element. -->
<!ELEMENT name (#PCDATA)><!-- The name of the producer -->
<!ELEMENT country (#PCDATA)><!-- The country where the company does its primary business -->
<!ELEMENT year (#PCDATA)><!-- The year of the album's release -->
<!ELEMENT info (link*, bibl*)><!-- Additional info, including links and bibliography information -->
<!ELEMENT link (#PCDATA)><!-- Links where people can read more about the album -->
<!ELEMENT bibl (#PCDATA)><!-- Bibliography text about the artist -->
]>
<catalog>
<cd>
<ent_seq>1</ent_seq>
<title>For Your Love</title>
<artist>
<name>The Yardbirds</name>
<name>Eric Clapton</name>
<nickname>Slowhand</nickname>
</artist>
<country>USA</country>
<country>UK</country>
<company>
<name>Sweet Music</name>
<country>USA</country>
</company>
<year>1965</year>
<info>
<link>http://en.wikipedia.org/wiki/For_Your_Love</link>
</info>
</cd>
<cd>
<ent_seq>2</ent_seq>
<title>Splish Splash</title>
<artist>
<name>Roberto Carlos</name>
<nickname>The King</nickname>
</artist>
<country>USA</country>
<country>Brazil</country>
<country>Italy</country>
<company>
<name>Sweet Music</name>
<country>Brazil</country>
</company>
<year>1965</year>
</cd>
<cd>
<ent_seq>3</ent_seq>
<title>How Great Thuo Art</title>
<artist>
<name>Elvis Presley</name>
<nickname>The King</nickname>
<nickname>The King of Rock 'n Roll</nickname>
</artist>
<country>USA</country>
<country>Canada</country>
<country>UK</country>
<company>
<name>Felton Jarvis</name>
<country>USA</country>
</company>
<year>1965</year>
</cd>
<cd>
<ent_seq>4</ent_seq>
<title>Big Willie style</title>
<artist>
<band>Will Smith</band>
<name>Will Smith</name>
</artist>
<country>USA</country>
<company>Columbia</company>
<year>1997</year>
</cd>
<cd>
<ent_seq>5</ent_seq>
<title>Empire Burlesque</title>
<artist>
<band>Bob Dylan and Boby Rockhammer</band>
<name>Bob Dylan</name>
<name>Boby Rockhammer</name>
</artist>
<country>USA</country>
<country>India</country>
<company>Columbia</company>
<year>1985</year>
</cd>
<cd> <!-- Update part 1: New Entry -->
<ent_seq>6</ent_seq>
<title>Merry Christmas</title>
<title>White Christmas</title>
<artist>
<name>Bing Crosby</name>
<artist>
<country>USA</country>
<company>MCA Records</company>
<year>1995</year>
</cd> <!-- End update part 1-->
</catalog>
Real-world example of desired output sample:
<datatable>
<table id="album title">
<title id="1">For your Love</title>
<title id="2">Splish Splash</title>
<title id="3">How Great Thuo Art</title>
<title id="4">Big Willie style</title>
<title id="5">Empire Burlesque</title>
<title id="6">Merry Christmas</title> <!-- Update part 2: New output -->
<title id="7">White Christmas</title> <!-- Update part 2: New output -->
</table>
<table id="Band Name">
<artist id="1">The Yardbirds</artist>
<artist id="2">Roberto Carlos</artist>
<artist id="3">Elvis Presley</artist>
<artist id="4">Will Smith</artist>
<artist id="5">Bob Dylan and Boby Rockhammer</artist>
<artist id="6"> <!-- Update part 2: New output -->
</table>
<table id="artist name">
<artist id="1">Eric Clapton</artist>
<artist id="2">Roberto Carlos</artist>
<artist id="3">Elvis Presley</artist>
<artist id="4">Will Smith</artist>
<artist id="5">Bob Dylan</artist>
<artist id="6">Boby Rockhammer</artist>
<artist id="7">Bing Crosby</artist> <!-- Update part 2: New output -->
</table>
<table id="nickname">
<nickname id="1">Slowhand</nickname>
<nickname id="2">The King</nickname>
<nickname id="3">The King of Rock 'n Roll</nickname>
</table>
</datatable>
and
<intermediarytable>
<table id="artist by band name">
<entry id="1">
<band_id>1</band_id>
<artist_id>1</artist_id>
</entry>
<entry id="2">
<band_id>2</band_id>
<artist_id>2</artist_id>
</entry>
<entry id="3">
<band_id>3</band_id>
<artist_id>3</artist_id>
</entry>
<entry id="4">
<band_id>4</band_id>
<artist_id>4</artist_id>
</entry>
<entry id="5">
<band_id>5</band_id>
<artist_id>5</artist_id>
</entry>
<entry id="6">
<band_id>5</band_id>
<artist_id>6</artist_id>
</entry>
<entry id="7">
<band_id>6</band_id>
<artist_id>7</artist_id>
</entry>
</table>
<table id="artist by nickname">
<entry id="1">
<artist_id>1</artist_id>
<nickname_id>1</artist_id>
</entry>
<entry id="2">
<artist_id>2</artist_id>
<nickname_id>2</nickname_id>
</entry>
<entry id="3">
<artist_id>2</artist_id>
<nickname_id>3</nickname_id>
</entry>
<entry id="4">
<artist_id>3</artist_id>
<nickname_id>3</nickname_id>
</entry>
</table>
</intermediarytable>
--UPDATE-- There's an issue in which two elements share the same entry ID
In another XML doc I have,
<entry id="1">
<word>blue</word>
<word>beryl</word>
<word lang="SP">azul</word>
</entry>
and I want the output to be
Data Tables:
<table id="en">
<word lang="en" id="0">blue</word>
<word lang="en" id="1">beryl</word>
</table>
<table id="sp">
<word lang="sp" id="0">azul</word>
</table>
Intermediary Table:
<table id="translation id">
<en_sp id="0"> <!-- en_sp means English-to-Spanish -->
<en>0</en>
<sp>0</sp>
</en_sp>
<en_sp>
<en>1</en>
<sp>0</sp>
</en_sp>
</table>
--UPDATES
Assuming an xml like this:
<catalog>
<cd>
<entry id="1">
<word>blue</word>
<word>beryl</word>
<word lang="SP">azul</word>
</entry>
</cd>
<cd>
<entry id="2">
...
try this:
$super = array();
$url = "original.xml";
if ($xml = #simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA)) {
foreach($xml->cd as $cd) {
foreach ($cd->entry as $entry) {
$id = (string)$entry['id'];
foreach($entry->word as $word) {
$lang = isset($word['lang']) ? (string)$word['lang'] : 'EN';
$super[$id][$lang][] = (string)$word;
}
}
}
}
display using:
print "<pre>";
print_r($super);
print "</pre>";
note: this is another approach, substantially what you need to understand when working with xml object and more in general with arrays is that you can store data by creating a structured hierarchy based on parent -> child; in this case i'm have created an array like this $super[$id][$lang][] = (string)$word; where $id is parent of $lang that is parent of $word that is respectively child of both; this will produce an array like this:
Array
(
[1] => Array
(
[EN] => Array
(
[0] => blue
[1] => beryl
)
[SP] => Array
(
[0] => azul
)
)
...
other things to consider are,
how to get the properties of matched tags like id or lang, in my example i have used $entry['id'] but $cd->entry['id'] is also valid.
how to convert an xml-dom-object into a valid string, so that you can reuse it as array index or value like (string)$word
from what i can see from your examples:
<catalog>
<cd>
<ent_seq>1</ent_seq>
<title>For Your Love</title>
<artist>
...
try this
$super = array();
$url = "original.xml";
if ($xml = #simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA)) {
$xml_array = #json_decode(#json_encode($xml), 1);
foreach ($xml_array['cd'] as $val) {
$key = $val['ent_seq'];
if (is_array($val)) {
foreach ($val as $k1 => $v1) {
if (is_array($v1)) {
switch ($k1) {
case 'artist':
foreach ($v1 as $k2 => $v2) {
if (is_array($v2)) {
foreach ($v2 as $v3) {
$super[$k2][$key] = $v3;
}
}
else {
$super[$k2][$key] = $v2;
}
}
break;
}
}
else {
switch ($k1) {
case 'title':
$super[$k1][$key] = $v1;
break;
}
}
}
}
}
}
display the results iterating through the array like this:
foreach( $super as $key => $val) {
echo "<table id='{$key}'>\n";
foreach($val as $key2 => $val2) {
echo "<$key id='$key2'> " . $val2." </$key>\n";
}
echo "</table>\n";
}
in order to have a better view of the array struct you can print it like this:
print "<pre>";
print_r($super);
print "</pre>";
this will display an array like this:
Array
(
[title] => Array
(
[1] => For Your Love
[2] => Splish Splash
[3] => How Great Thuo Art
[4] => Big Willie style
[5] => Empire Burlesque
)
[name] => Array
(
[1] => Eric Clapton
[2] => Roberto Carlos
[3] => Elvis Presley
[4] => Will Smith
[5] => Boby Rockhammer
)
[nickname] => Array
(
[1] => Slowhand
[2] => The King
[3] => The King of Rock 'n Roll
)
[band] => Array
(
[4] => Will Smith
[5] => Bob Dylan and Boby Rockhammer
)
)
note: as you can see i made use of switch-case, cause your xml-tags are not always the same consistence and they have similar-name in some circumstances like <company><name> and <artist><name>; you can create your own cases.
however as is now, it work well with the fields you want to grab as in da example.
Just to clarify, you are trying to take an input XML document, convert it to another (differently formatted) xml document using XSL/T, and then take the resulting XML and store it in your MySQL database?
I'm new to stack overflow, so I'm not sure how add a comment to the original post.

Simple XML reading question (PHP)

I have the following XML file:
<?xml version="1.0" encoding="utf-8"?>
<SearchResults:searchresults xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.zillow.com/static/xsd/SearchResults.xsd /vstatic/279989c5e93d519f8d8f23d3f6cac661/static/xsd/SearchResults.xsd" xmlns:SearchResults="http://www.zillow.com/static/xsd/SearchResults.xsd">
<request>
<address>2114 Bigelow Ave</address>
<citystatezip>Seattle, WA</citystatezip>
</request>
<message>
<text>Request successfully processed</text>
<code>0</code>
</message>
<response>
<results>
<result>
<zpid>48749425</zpid>
<links>
<homedetails>http://www.zillow.com/homedetails/2114-Bigelow-Ave-N-Seattle-WA-98109/48749425_zpid/</homedetails>
<graphsanddata>http://www.zillow.com/homedetails/charts/48749425_zpid,1year_chartDuration/?cbt=3697699817560038867%7E3%7EQh4sEjEhBNEguUWA-0f22TvGUpBB7FpUkAZlBRy5_26R5PYjKDdVAA**</graphsanddata>
<mapthishome>http://www.zillow.com/homes/48749425_zpid/</mapthishome>
<myestimator>http://www.zillow.com/myestimator/Edit.htm?zprop=48749425</myestimator>
<myzestimator deprecated="true">http://www.zillow.com/myestimator/Edit.htm?zprop=48749425</myzestimator>
<comparables>http://www.zillow.com/homes/comps/48749425_zpid/</comparables>
</links>
<address>
<street>2114 Bigelow Ave N</street>
<zipcode>98109</zipcode>
<city>Seattle</city>
<state>WA</state>
<latitude>47.63793</latitude>
<longitude>-122.347936</longitude>
</address>
<zestimate>
<amount currency="USD">1112500</amount>
<last-updated>01/14/2010</last-updated>
<oneWeekChange deprecated="true"></oneWeekChange>
<valueChange duration="30" currency="USD">-77500</valueChange>
<valuationRange>
<low currency="USD">878875</low>
<high currency="USD">1145875</high>
</valuationRange>
<percentile>0</percentile>
</zestimate>
<localRealEstate>
<region id="271856" type="neighborhood" name="East Queen Anne">
<zindexValue>525,252</zindexValue>
<zindexOneYearChange>-0.104</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/East-Queen-Anne/r_271856/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/East-Queen-Anne-Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/homes/for_sale/East-Queen-Anne-Seattle-WA/</forSale>
</links>
</region>
<region id="16037" type="city" name="Seattle">
<zindexValue>373,795</zindexValue>
<zindexOneYearChange>-0.064</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/r_16037/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/homes/for_sale/Seattle-WA/</forSale>
</links>
</region>
<region id="59" type="state" name="Washington">
<zindexValue>256,760</zindexValue>
<zindexOneYearChange>-0.074</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-home-value/r_59/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/WA/</forSaleByOwner>
<forSale>http://www.zillow.com/homes/for_sale/WA/</forSale>
</links>
</region>
</localRealEstate>
</result>
</results>
</response>
</SearchResults:searchresults>
<!-- H:118 T:102ms S:1761 R:Fri Jan 15 10:52:49 PST 2010 B:3.0.79367-comp_rel_b -->
If you can't already tell, it's the standard output of the Zillow API. I want to store the data of information stored between certain tags, which I have learned is queried through the xpath.
For example, how would I query for the data in /SearchResults:searchresults/request/address? Doing something like this doesn't work when I echo/print the variable:
$xml = simplexml_load_file("-truncated XML URL-");
$result = $xml->xpath('/SearchResults:searchresults/request/address')
From what I understand, the $result variable should contain the value found nested in that %VALUE HERE%, correct? But it prints "Array", and when I print_r, it returns blank.
Here's a simple way to get that information:
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->request->address;
?>
You need to use the full namespace not the short name.
Use http://simplepie.org
$xml = "yourxml code here";
$feed = new SimplePie();
$feed->set_raw_data($xml);
$feed->init();
$feed->handle_content_type();
echo $feed->get_adress();

Categories