i haven't really worked with xml files before, but now i'm trying to get an xml file into a php array or object.
the xml file looks like this: (it's for translating a web app)
<?xml version="1.0" ?>
<content language="de">
<string name="login">Login</string>
<string name="username">Benutzername</string>
<string name="password">Passwort</string>
</content>
i tried the following:
$xml = new SimpleXMLElement("de.xml", 0, 1);
print_r($xml);
unfortunately, the values of the 'name' attribute are for some reason not in the php object. i'm looking for a way that allows me to retrieve the xml values by the name attribute.
for instance:
$xml['username'] //returns "Benutzername"
how can this be done?
appreciate your help :) cheers!
This one should explain the function to you:
<?php
$xml = simplexml_load_file('de.xml');
foreach($xml->string as $string) {
echo 'attributes: '. $string->attributes() .'<br />';
}
?>
The attributes() method from SimpleXMLElement class will help you - http://de.php.net/manual/en/simplexmlelement.attributes.php
$xmlStr = <<<XML
<?xml version="1.0" ?>
<content language="de">
<string name="login">Login</string>
<string name="username">Benutzername</string>
<string name="password">Passwort</string>
</content>
XML;
$doc = new DomDocument();
$doc->loadXML($xmlStr);
$strings = $doc->getElementsByTagName('string');
foreach ($strings as $node) {
echo $node->getAttribute('name') . ' = ' . $node->nodeValue . PHP_EOL;
}
You can use an xpath expression to get the element with the name you are looking for:
(string)current($xml->xpath('/content/string[#name="username"]'))
Related
I am trying to parse XML with PHP. The XML is a response from ebay getsellerlist api, and is structured like so:
<!--?xml version="1.0" encoding="UTF-8"?-->
<getsellerlistresponse xmlns="urn:ebay:apis:eBLBaseComponents">
<timestamp>2016-08-11T14:17:39.869Z</timestamp>
<ack>Success</ack>
<version>967</version>
<build>E967_CORE_APISELLING_17965876_R1</build>
<itemarray>
<item>
<itemid>itemid1</itemid>
<listingdetails>
<viewitemurl>itemurl1</viewitemurl>
</listingdetails>
<primarycategory>
<categoryid>categoryid1</categoryid>
<categoryname>categoryname1</categoryname>
</primarycategory>
<title>title1</title>
<picturedetails>
<galleryurl>url1</galleryurl>
<photodisplay>thumbnail1</pictureurl>
<pictureurl>picture1</pictureurl>
</picturedetails>
</item>
</itemarray>
</getsellerlistresponse>
My php is as follows:
<?
$xml = '<!--?xml version="1.0" encoding="UTF-8"?--><getsellerlistresponse xmlns="urn:ebay:apis:eBLBaseComponents"><timestamp>2016-08-11T14:17:39.869Z</timestamp><ack>Success</ack><version>967</version><build>E967_CORE_APISELLING_17965876_R1</build><itemarray><item><itemid>itemid1</itemid><listingdetails><viewitemurl>itemurl1</viewitemurl></listingdetails><primarycategory><categoryid>categoryid1</categoryid><categoryname>categoryname1</categoryname></primarycategory><title>title1</title><picturedetails><galleryurl>url1</galleryurl><photodisplay>thumbnail1</pictureurl><pictureurl>picture1</pictureurl></picturedetails></item><item><itemid>itemid2</itemid><listingdetails><viewitemurl>itemurl2</viewitemurl></listingdetails><primarycategory><categoryid>categoryid2</categoryid><categoryname>categoryname2</categoryname></primarycategory><title>title1</title><picturedetails><galleryurl>url2</galleryurl><photodisplay>thumbnail2</pictureurl><pictureurl>picture2</pictureurl></picturedetails></item></itemarray></getsellerlistresponse>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$title_nodes = $dom->getElementsByTagName('title');
$titles = array();
foreach ($title_nodes as $node) {
$titles[] = $node->nodeValue;
echo $node->nodeValue;
}
echo $titles[0];
echo count($titles);
?>
When I run it, I get a blank page, no errors, nothing.
If I check $titles length using count(), it comes back as zero.
For some reason it is not getting the title node (or any other nodes) and I can't figure out how to parse the xml string with php and get the node values.
Any help most appreciated, if the question is vague or lacking detail, please let me know and I will correct it.
The XML isn't valid:
Unable to parse any XML input. org.jdom2.input.JDOMParseException: Error on line 2: The element type "photodisplay" must be terminated by the matching end-tag "".
And that's only after you remove the comments in your XML declaration:
<!--?xml version="1.0" encoding="UTF-8"?-->
shoud be
<?xml version="1.0" encoding="UTF-8"?>
Working demo:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<getsellerlistresponse xmlns="urn:ebay:apis:eBLBaseComponents">
<timestamp>2016-08-11T14:17:39.869Z</timestamp>
<ack>Success</ack>
<version>967</version>
<build>E967_CORE_APISELLING_17965876_R1</build>
<itemarray>
<item>
<itemid>itemid1</itemid>
<listingdetails>
<viewitemurl>itemurl1</viewitemurl>
</listingdetails>
<primarycategory>
<categoryid>categoryid1</categoryid>
<categoryname>categoryname1</categoryname>
</primarycategory>
<title>title1</title>
<picturedetails>
<galleryurl>url1</galleryurl>
<photodisplay>thumbnail1</photodisplay>
<pictureurl>picture1</pictureurl>
</picturedetails>
</item>
</itemarray>
</getsellerlistresponse>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$title_nodes = $dom->getElementsByTagName('title');
$titles = array();
foreach ($title_nodes as $node) {
$titles[] = $node->nodeValue;
echo $node->nodeValue;
}
echo $titles[0];
echo count($titles);
Would anyone know how i can "explode" a string back into "normal" xml format?
I found this script (ref:gooseflight,2010) that looks like it can do the job but the output comes out stuck together.
Here's the code:
enter code herefunction combineXML($file)
{
global $xmlstr;
$xml = simplexml_load_file($file);
foreach($xml as $element)
$xmlstr .= $element->asXML();
}
$files[] = "tmp.xml";
$files[] = "traduction.xml";
$xmlstr = '<CAB>';
foreach ($files as $file)
combineXML($file);
$xmlstr .= '</CAB>';
// Convert string to XML for further processing
$xml = simplexml_load_string($xmlstr);
$bytes = file_put_contents("combined.xml", $xml->asXML())
Here is the output:
<?xml version="1.0" encoding="UTF-8"?>
<CAB>
<CABO>XXXXXXXXXX0987650003</CABO><ACTIVITY>NONE</ACTIVITY><BEORI>blablaE</BEORI>BEDEST>blabla</BEDEST><NATRELA>more blabla</NATRELA><ANE>2014</ANE><NODEP>1111</NODEP>
</CAB>
So how could i seperate the nodes to look like this?:
<?xml version="1.0" encoding="UTF-8"?>
<CAB>
<CABO>XXXXXXXXXX0987650003</CABO>
<ACTIVITY>NONE</ACTIVITY>
<BEORI>blablaE</BEORI>
<BEDEST>blabla</BEDEST>
<NATRELA>more blabla</NATRELA>
<ANE>2014</ANE>
<NODEP>1111</NODEP>
.....
</CAB>
Would anyone know how to fix it?
I would suggest to use DomDocument class to save the XML; check this:
$dom_obj = new DOMDocument();
$dom_obj->loadXML($file);
// Do all your changes to the file by using DomDocument command (e.g. CreateElement, CreateAttribute, etc)
$dom_obj->formatOutput = true;
$dom_obj->save($file);
Not too sure what I'm doing wrong with parsing/reading an xml document.
My guess is that it's not standardized, and I'm going to need a different process to read anything from the string.
If that's the case, then I'm rather excited to learn how someone would read the xml.
Here's what I've got, and what I'm doing.
example.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="someurl.php"?>
<response>
<status>Error</status>
<error>The error message I need to extract, if the status says Error</error>
</response>
read_xml.php
<?php
$content = 'example.xml';
$string = file_get_contents($content);
$xml = simplexml_load_string($string);
print_r($xml);
?>
I'm getting no result back from the print_r.
I switched the xml to something more standard, like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
...and it worked fine. So I'm sure it's due to a non-standard format, passed back from the source I'm getting it from.
How would I extract the <status> and <error> tags?
Tek has a good answer, but if you want to use SimpleXML, you can try something like this:
<?php
$xml = simplexml_load_file('example.xml');
echo $xml->asXML(); // this will print the whole string
echo $xml->status; // print status
echo $xml->error; // print error
?>
EDIT: If you have multiple <status> and <error> tags in your XML, have a look at this:
$xml = simplexml_load_file('example.xml');
foreach($xml->status as $status){
echo $status;
}
foreach($xml->error as $error){
echo $error;
}
I'm assuming <response> is your root. If it isn't, try $xml->response->status and $xml->response->error.
I prefer to use PHP's DOMDocument class better.
Try something like this:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="someurl.php"?>
<response>
<status>Error</status>
<error>The error message I need to extract, if the status says Error</error>
</response>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$statuses = $dom->getElementsByTagName('status');
foreach ($statuses as $status) {
echo "The status tag says: " . $status->nodeValue, PHP_EOL;
}
?>
Demo: http://codepad.viper-7.com/mID6Hp
I have this XML
<parent>
<sms>
<response>
<message>message</message>
<reponse>text<response>
</response>
</sms>
<sms>
<response>
<message>message</message>
<reponse>text2<response>
</response>
</sms>
</parent>
I want to get the whole contents of response tag i.e <reponse1>text<response1> , <reponse2>text<response2> .which i will strore in an array. what i tried id
function xmlSplitUpResponseXML($xmlvalue)
{
$returnSplit = array();
$r = 0;
if(simplexml_load_string($xmlvalue))
{
$xml = simplexml_load_string($xmlvalue);
foreach($xml->children() as $child)
{
if(strtolower($child->getName())=='sms')
{
foreach ($child as $fields):
if(strtolower($fields->getName())=='response')
{
echo $fields;
}
}
} }
}
But the text is not echoed.
how can i do this.
Your XML isn't completly correct, but when fixed - try this:
echo $fields->message."<br>";
echo $fields->response."<hr>";
Works on your given example, with this fixed xml:
$string = "<parent><sms><response><message>message</message><response>text</response></response></sms><sms><response><message>message</message><response>text2</response></response></sms></parent>";
Hmm, seems like you need some XPath to the rescue...
Given the following fixed-up XML (note nested response nodes)
<parent>
<sms>
<response>
<message>message</message>
<response>text</response>
</response>
</sms>
<sms>
<response>
<message>message</message>
<response>text2</response>
</response>
</sms>
</parent>
The following PHP will do it for you.
<?php
$xml = simplexml_load_file( "sms.xml" );
// Find the sms response (note responses are nested in a parent response for some reason
$result = $xml->xpath('/parent/sms/response/response');
while(list( , $node) = each($result)) {
// to just output the value of the node
// echo $node;
// to wrap value in tags *bad idea*
echo $node->asXML();
}
?>
Not sure why you'd want to return an XML string, seems like a bad idea to me. What are you
doing with the output? Probably better to construct an XML document properly, just guessing...
<?xml version="1.0" encoding="ISO-8859-2"?>
<!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
<pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
<pasaz:Body>
<loadOffers xmlns="urn:ExportB2B">
<offers />
</loadOffers>
</pasaz:Body>
</pasaz:Envelope>
I've to add some child nodes to "offers" node and I'm using SimpleXML.
The PHP code: $offer = $xml->offers->addChild('offer') returns an error.
It's all wrong because I've got problem with handling namespaces in SimpleXML! Please help!
E.g. by using xpath the get the target/parent element.
<?php
$envelope = new SimpleXMLElement('<?xml version="1.0" encoding="ISO-8859-2"?>
<!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
<pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
<pasaz:Body>
<loadOffers xmlns="urn:ExportB2B">
<offers />
</loadOffers>
</pasaz:Body>
</pasaz:Envelope>');
$envelope->registerXPathNamespace('pasaz', 'http://schemas.xmlsoap.org/soap/envelope/');
$envelope->registerXPathNamespace('b2b', 'urn:ExportB2B');
$ns = $envelope->xpath('//pasaz:Body/b2b:loadOffers/b2b:offers');
if ( 0<count($ns) ) {
$offers = $ns[0];
$offers->a = 'abc';
$offers->x = 'xyz';
}
echo $envelope->asXml();
prints
<?xml version="1.0" encoding="ISO-8859-2"?>
<!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
<pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
<pasaz:Body>
<loadOffers xmlns="urn:ExportB2B">
<offers><a>abc</a><x>xyz</x></offers>
</loadOffers>
</pasaz:Body>
</pasaz:Envelope>