I want to get the value present in xml node for that I written following code.
The code aim is to get
1.Board value,
2.Address->City value,
3.Photo->PropertyPhoto->SequenceId value.
Code is:
//some code
$fsp = $xml->saveXML();
echo $fsp; //it's output is given below
$s = simplexml_import_dom($fsp);
echo $s->PropertyDetails[0]->Board;
echo $s->PropertyDetails[0]->Address->City;
echo $s->PropertyDetails[0]->Photo->PropertyPhoto->SequenceId;
OUTPUT OF echo $fsp is:
<?xml version="1.0" encoding="UTF-8"?>
<PropertyDetails ID="13953882" LastUpdated="Thu, 09 Jan 2014 01:43:48 GMT">
<ListingID>188691</ListingID>
<Board>117</Board>
<Address>
<StreetAddress>B LOCAL RD</StreetAddress>
<AddressLine1>B LOCAL RD</AddressLine1>
<City>PORT REXTON</City>
<Province>Newfoundland & Labrador</Province>
<PostalCode>A0C2H0</PostalCode>
<Country>Canada</Country>
</Address>
<Photo>
<PropertyPhoto>
<SequenceId>1</SequenceId>
</PropertyPhoto>
<PropertyPhoto>
<SequenceId>12</SequenceId>
</PropertyPhoto>
</Photo>
<ViewType>Ocean view</ViewType>
It doesn't given any output.
Output required is:
117
PORT REXTON
1,12
Help me.
A couple things I see here. First of all, your XML is not properly formatted. Your PropertyDetails tag is not closed. So close that out, and instead of using a DOMDocument, use the SimpleXMLElement class.
First your XML needs to corrected like thus:
<?xml version="1.0" encoding="UTF-8"?>
<PropertyDetails ID="13953882" LastUpdated="Thu, 09 Jan 2014 01:43:48 GMT">
<ListingID>188691</ListingID>
<Board>117</Board>
<Address>
<StreetAddress>B LOCAL RD</StreetAddress>
<AddressLine1>B LOCAL RD</AddressLine1>
<City>PORT REXTON</City>
<Province>Newfoundland & Labrador</Province>
<PostalCode>A0C2H0</PostalCode>
<Country>Canada</Country>
</Address>
<Photo>
<PropertyPhoto>
<SequenceId>1</SequenceId>
</PropertyPhoto>
<PropertyPhoto>
<SequenceId>12</SequenceId>
</PropertyPhoto>
</Photo>
<ViewType>Ocean view</ViewType>
</PropertyDetails>
Notice the last line.
Now use SimpleXMLElement and you will be close to accessing the way you want.
$s = new SimpleXMLElement($fsp);
echo $s->Board;
echo $s->Address->City;
$sequence_ids = array();
foreach($s->Photo->PropertyPhoto as $PropertyPhoto)
$sequence_ids[] = $PropertyPhoto->SequenceId;
echo implode(',',$sequence_ids);
Since is your root node in the XML, you dont need to access it via ->PropertyDetails[0]. It knows.
Hope this helps.
First load the xml from the string within your var:
$doc = new DOMDocument();
$doc->load($fsp);
apidoc here: http://www.php.net/manual/en/domdocument.loadxml.php
And then read the tags requested:
//board
$boards = $doc->getElementsByTagName('Board');
echo $boards[0]->nodeValue, PHP_EOL;
//city
$cities = $doc->getElementsByTagName('City');
echo $cities[0]->nodeValue, PHP_EOL;
//sequence ids
$arrIds = array();
foreach ($doc->getElementsByTagName('SequenceId') as $sid) $arrIds[] = $sid->nodeValue;
echo implode(',', $arrIds);
This assumes you only have only one listing within your file! Otherwise you have to do the tag-lookups depending on parent-nodes (not on global document).
Hope this helps!
Related
I have an XML file with the root element name wwwjob. This root element contains attributes, I need to access the value of the 'method' attribute to be able to update various database entries.
This is a little bit of a learning curve at the moment.
<?xml version="1.0" encoding="iso-8859-1"?>
<wwwjob id="32cca11IACH" method="Delete">
some more xml stuff
</wwwjob>
Ive tried:
<?php $xml = $vacancyXML->wwwjob['method']; ?>
This just gave me 'NULL'.
Ive also tried:
<?php $xml = $vacancyXML->getName(); ?>
This just spits out the name 'wwwjob'.
I need to store the method (Delete/Update/Add) as a variable for use in later parts of the function.
Thanks
When loadinG to simplexml, attributes of the root element became attributes of the simpleXml object. So, you can get it just
$str = '<?xml version="1.0" encoding="iso-8859-1"?>
<wwwjob id="32cca11IACH" method="Delete">
</wwwjob>';
$vacancyXML = simplexml_load_string($str);
echo $vacancyXML['method']; // Delete
demo
You can get the attributes of the root element with SimpleXMLElement::attributes():
$www = new SimpleXMLElement($xml);
echo $www->attributes()->method; // Delete
Demo
I'm trying to use php to delete an xml element but it doesn't work. I tried some different code but no one works. I would also like to use cookies to get element in the future. Can you suggest me what I have to do ? I'm not expert and for this I'm in difficulty.
Here the code:
<?php
$dom = new DOMDocument();
$dom->load("Dati.xml");
$matchingElements = $dom->getElementsByTagName("Matematica");
$totalMatches = $matchingElements->length;
$elementsToDelete = array();
$elementsToDelete[] = $matchingElements->item(0);
foreach ( $elementsToDelete as $elementToDelete ) {
$elementToDelete->parentNode->removeChild($elementToDelete);
}
$dom->save($xmlFileToLoad);
echo "<script type='text/javascript'>";
echo "window.close();";
echo "</script>";
echo "Puoi chiudere questa pagina";
?>
Here the xml:
<?xml version="1.0" encoding="UTF-8"?>
<document>
<Informatica>
<nome>aaaa</nome>
<classe>3C</classe>
<titolo>Informatica</titolo>
<materia>Informatica</materia>
<ISBN>123456789101112</ISBN>
<prezzo>12</prezzo>
<autori>tizio</autori>
<contatto>nanni-lombardo1#hotmail.it</contatto>
<codice>123456</codice>
</Informatica>
<Matematica>
<nome>bbb</nome>
<classe>3C</classe>
<titolo>math</titolo>
<materia>Matematica</materia>
<ISBN>123456789101112</ISBN>
<prezzo>12</prezzo>
<autori>tizio</autori>
<contatto>nanni-lombardo1#hotmail.it</contatto>
<codice>123456</codice>
</Matematica>
</document>
Please be sure to :
Remove the space before your XML start tag
Define your $xmlFileToLoad variable
Make your destination XML writable (see Chmod & permissions)
My test file works fine : https://eu.andredasilva.fr/testandre/test.php (source code : https://eu.andredasilva.fr/testandre/test.php.source)
Base XML : https://eu.andredasilva.fr/testandre/Dati.xml
Result XML : https://eu.andredasilva.fr/testandre/test.xml
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.
I was tesing with a simple example of how to display XML in browser using PHP and found this example which works good
<?php
$xml = new DOMDocument("1.0");
$root = $xml->createElement("data");
$xml->appendChild($root);
$id = $xml->createElement("id");
$idText = $xml->createTextNode('1');
$id->appendChild($idText);
$title = $xml->createElement("title");
$titleText = $xml->createTextNode('Valid');
$title->appendChild($titleText);
$book = $xml->createElement("book");
$book->appendChild($id);
$book->appendChild($title);
$root->appendChild($book);
$xml->formatOutput = true;
echo "<xmp>". $xml->saveXML() ."</xmp>";
$xml->save("mybooks.xml") or die("Error");
?>
It produces the following output:
<?xml version="1.0"?>
<data>
<book>
<id>1</id>
<title>Valid</title>
</book>
</data>
Now I have got two questions regarding how the output should look like.
The first line in the xml file '', should not be displayed, that is it should be hidden
How can I display the TextNode in the next line. In total I am exepecting an output in this fashion
<data>
<book>
<id>1</id>
<title>
Valid
</title>
</book>
</data>
Is that possible to get the desired output, if so how can I accomplish that.
Thanks
To skip the XML declaration you can use the result of saveXML on the root node:
$xml_content = $xml->saveXML($root);
file_put_contents("mybooks.xml", $xml_content) or die("cannot save XML");
Please note that saveXML(node) has a different output from saveXML().
First question:
here is my post where all usable threads with answers are listed: How do you exclude the XML prolog from output?
Second question:
I don't know of any PHP function that outputs text nodes like that.
You could:
read xml using DomDocument and save each node as string
iterate trough nodes
detect text nodes and add new lines to xml string manually
At the end you would have the same XML with text node values in new line:
<node>
some text data
</node>
<?php
$doc = new DOMDocument();
$doc->load('http://weather.yahooapis.com/forecastrss?p=VEXX0024&u=c');
$channel = $doc->getElementsByTagName("channel");
foreach($channel as $chnl)
{
$item = $chnl->getElementsByTagName("item");
foreach($item as $itemgotten)
{
$describe = $itemgotten->getElementsByTagName("description");
$description = $describe->item(0)->nodeValue;
echo $description;
}
}
?>
And as you can see is a simple script who return the content of the tag from the above url. The thing is that i dont need that content, i need the one who is inside the tag . I need the attributes code, temp, text. How do i do that simple with my actual code? Thanks
Ex of the tag content:
<yweather:condition text="Partly Cloudy" code="30" temp="30" date="Fri, 16 Jul 2010 8:30 am AST" />
Something like:
echo $itemgotten->getElementsByTagNameNS(
"http://xml.weather.yahoo.com/ns/rss/1.0","condition")->item(0)->
getAttribute("temp");
The key is that you have to use getElementsByTagNameNS instead of getElementsByTagName and specify "http://xml.weather.yahoo.com/ns/rss/1.0" as the namespace.
You know yweather is a shortcut for http://xml.weather.yahoo.com/ns/rss/1.0 because the XML file includes a xmls attribute:
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
How about:
DOMElement::getAttribute — Returns value of attribute
And if you need to get anything with namespaces, there is corresponding methods ending in NS.