I'm confused about parsing XML in PHP - php

How can I parse XML data using PHP? I want to get the contents of just the element named
<profile xmlns="mysite.com">
<confirmationNumber>128686132</confirmationNumber>
<merchantRefNum>123456</merchantRefNum>
<customerEmail>test#test.com</customerEmail>
</profile>
I was trying to use this code
$sxe = new SimpleXMLElement($decodedMessage);
echo $sxe->getName() . "\n";
foreach ($sxe->children() as $child)
{
echo $child->getName() . "\n";
}
But I don't know how to select a specific element.

You don't need the traversal methods of SimpleXML. Just use simplexml_load_string() if you already have it in one:
$xml = simplexml_load_string($decodedMessage);
Then accessing the content is as simple as:
print $xml->customerEmail;

You can try the function simplexml_load_file(), and use the XML as object. Or convert to array with cast.

You should look at xpath.

One of the easiest ways to deal with it is look for a function on google called xml2array, since associative arrays are much easier to deal with in PHP than XML.

you can try this.
$xml = simplexml_load_file($filePath) or die ("Unable to load XML file!");
//Access XML Data
echo "confirmation Number: " . $xml->confirmationNumber;
echo "merchant Ref Num: " . $xml->confirmationNumber;
echo "customer Email: " . $xml->customerEmail;

If you want to find that one element within a larger document, you could use XPath.
For example, for the XML
<some>
<hierarchy>
<profile>
<etc>et cetera</etc>
</profile>
</hierarchy>
</some>
you can simply do $sxe->xpath('//profile'), which will return an array of all the profile elements everywhere in the document (as SXEs, which you can then process). If there is only one profile element, then you're done, but if there are many you will need a more specific XPath.

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;

Retrieve XML element data with PHP

i'm trying to allow the user to retrieve a specific XML node and print the information. My XML data is as follows:
<people>
<person id="1">
<forename>Jim</forename>
<surname>Morrison</surname>
</person>
<person id="2">
<forename>James</forename>
<surname>Frank</surname>
</person>
</people>
I want to be able to search my XML document with a name or ID, for instance I want to be able to say, 'check that james exists, and if james does, print out his information, otherwise print out an error message'.
I've figured that I first need to include the file with:
$xml=simplexml_load_file("credentials.xml") or die("Error: Cannot create object");
From this point onwards i'm unsure how to proceed, i've looked at SimpleXML and XPATH but i'm unsure on how to use these to acheive this. Thanks if you can help
Let's xpath():
$xml = simplexml_load_string($x); // assume XML in $x
$result = $xml->xpath("/people/person[forename = 'James']")[0];
The above xpath-expression will select any <person> having 'James' as a <forename> and store it as an array in $result.
With the [0] at the end of line 2, we select only the first entry in that array and store it in $result. This requires PHP >= 5.4.
We could also write to get the same result:
$result = $xml->xpath("/people/person[forename = 'James']");
$result = $result[0];
If there were more than 1 James in the XML, we would only get the first.
To get all Jameses, do as in line 1 above.
Then, let's output the <person> selected by our xpath expression:
echo $result->forename . ' ' . $result->surname .' has id ' . $result['id'] . ".";
In case $result contains several Jameses, do:
foreach ($result as $person) {
echo $person->forename . ' ' . $person->surname .' has id ' . $person['id'] . "." . PHP_EOL;
}
see it working: https://eval.in/222195
You should use the manual.
simplexml_load_file returns a SimpleXMLElement object.
From here you can use the objects children method to get the children you want, which would also be more of that SimpleXMLElement objects. Let's say you first want the children called people, and then want person. When you got the person objects, you can get the value of the attribute by the method attributes to get the names and the values etc. Because SimpleXMLElement implements Traversable, you can use a foreach loop to loop through the lists/arrays you get in return.
Figured out how to mostly solve the problem with this:
$xml=simplexml_load_file("credentials.xml") or die("Error: Cannot create object");
foreach($xml->children() as $people){
if ($people->forename == "james" ){echo $people->forename;}
}
This may be inefficient so if anyone else has a better way please do specify :)

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;
} }

Modify xml nodes using DOM or SIMPLE XML?

I have source XML here: http://www.grilykrby.cz/rss/pf-heureka.xml. I want to use this xml feed and create another modified on my own server. I would like to change every node CATEGORYTEXT which contains word Prislusenstvi. I just tried something but I got only the listing of all categories without changing XML :-(
Here is the example of my code. The row $kategorie="nejaka kategorie"; doesn't work.
<?php
$file = "http://www.grilykrby.cz/rss/pf-heureka.xml";
$xml=simplexml_load_file($file);
foreach ($xml->xpath('//SHOPITEM/CATEGORYTEXT') as $kategorie) {
echo $kategorie."<br />";
$kategorie="nejaka kategorie";
}
file_put_contents('test.xml', $xml->asXML());
?>
$kategorie is just a temp variable used in the loop which contains a copy of the data returned by xpath query. You would need to actually set the value directly in the $xml object.
I would personally also consider doing a str_replace or preg_replace within the XML content itself before parsing it into a simpleXML object.
Final Accepted Answer
<?php
$xml = simplexml_load_file('http://www.grilykrby.cz/rss/pf-heureka.xml');
$i=0;
foreach($xml -> SHOPITEM as $polozka) {
if ($polozka -> CATEGORYTEXT == "Příslušenství") $xml -> SHOPITEM[$i] -> CATEGORYTEXT = "Some other text";
$i++;
}
?>

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