How do you retrieve the value in atom:id from a XML document?
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom">
<atom:id>http://www.google.com/m8/feeds/profiles/domain/mydomain.com/full/test</atom:id>
</atom:entry>
You can use SimpleXML and XPath for that:
$xml = <<<XML
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom">
<atom:id>http://www.google.com/m8/feeds/profiles/domain/mydomain.com/full/test</atom:id>
</atom:entry>
XML;
$xml = new SimpleXMLElement($xml);
$result = $xml->xpath('/atom:entry/atom:id');
foreach ($result as $curResult)
{
echo __FILE__ . ':' . __LINE__ . '<pre>' . print_r($curResult, 1) . '</pre>';
}
You could use simple_xml and an xpath query. Like so:
$xml = <<<EOF
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom">
<atom:id>http://www.google.com/m8/feeds/profiles/domain/mydomain.com/full/test</atom:id>
</atom:entry>
EOF;
$doc = simplexml_load_string($xml);
$el = $doc->xpath('//atom:id');
echo (string)$el[0];
(obviously that's without error checking and all)
Related
My XML is looking perfect but not working. I get a error on line 2 at column 1: Extra content at the end of the document
Other answers from other posts aren't helping
<?php
$csv = array_map(function($v){return str_getcsv($v, "|");},file('quotes.csv'));
$hdrs = array_shift($csv);
$count = 0;
$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<quotes>';
foreach($csv as $k=>$v) {
$xml .= '<record id="' . ++$count .'">';
foreach($hdrs as $h=>$i) {
$xml .= '<' . $i . '>' . htmlspecialchars($v[$h], ENT_XML1, 'UTF-8') . '</' . $i . '>';
}
$xml .= '</record>';
}
$xml .= '</quotes>';
header ("Content-Type:text/xml");
echo $xml;
?>
Expected Output
<quotes>
<record id="1">
<quote>There is no remedy but to love more.</quote>
<source>Henry David Thoreau</source>
<dob-dod>1817-1862</dob-dod>
<wplink>http://en.wikipedia.org/wiki/Henry_David_Thoreau</wplink>
<wpimg>http://upload.wikimedia.org/wikipedia/commons/f/f0/Benjamin_D._Maxham_-_Henry_David_Thoreau_-_Restored.jpg</wpimg>
<category>love</category>
</record>
</quotes>
Use the XMLWriter, its quite easy and it will generate valid XML. Doing your own manually is always likely to cause little anomalies.
$lines = array_map(function($v){return str_getcsv($v, "|");},file('quotes.csv'));
$hdrs = array_shift($lines);
$count = 0;
header ("Content-Type:text/xml");
$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->setIndent(true);
$xml->startElement('quotes');
foreach($lines as $line) {
$xml->startElement("record");
$xml->writeAttribute('id', ++$count);
foreach($hdrs as $i=>$name) {
$xml->writeElement($name, htmlspecialchars($line[$i], ENT_XML1, 'UTF-8') );
}
$xml->endElement();
}
$xml->endElement();
$xml->endDocument();
$xml->flush();
The XMLWriter Docs in the manual
Using this data
source|dob-dod|wplink|wpimg|category
Henry David Thoreau|1817-1862|http://en.wikipedia.org/wiki/Henry_David_Thoreau|http://upload.wikimedia.org/wikipedia/commons/f/f0/Benjamin_D._Maxham_-_Henry_David_Thoreau_-_Restored.jpg|love
Sir Benjamin Baker|1840-1907|https://en.wikipedia.org/wiki/Benjamin_Baker_(engineer)|https://en.wikipedia.org/wiki/Benjamin_Baker_(engineer)#/media/File:BBaker.jpg|Engineers
We get this result
<?xml version="1.0"?>
<quotes>
<record id="1">
<source>Henry David Thoreau</source>
<dob-dod>1817-1862</dob-dod>
<wplink>http://en.wikipedia.org/wiki/Henry_David_Thoreau</wplink>
<wpimg>http://upload.wikimedia.org/wikipedia/commons/f/f0/Benjamin_D._Maxham_-_Henry_David_Thoreau_-_Restored.jpg</wpimg>
<category>love</category>
</record>
<record id="2">
<source>Sir Benjamin Baker</source>
<dob-dod>1840-1907</dob-dod>
<wplink>https://en.wikipedia.org/wiki/Benjamin_Baker_(engineer)</wplink>
<wpimg>https://en.wikipedia.org/wiki/Benjamin_Baker_(engineer)#/media/File:BBaker.jpg</wpimg>
<category>Engineers</category>
</record>
</quotes>
I wanted to try to pick up Volume value from the Level1Data node.
Here is the xml:
<Response>
<Content>
<Level1Data Tick="U" Currency="USD" TickSize="0.0001000000" TickValue="0" AssetClass="Equity" InstrumentState="Open" LastPrice="24.1550" LotSize="10"
MinPermittedPrice="0" MaxPermittedPrice="0" ClosePrice="24.0300" OpenPrice="24.1500" FirstPrice="24.1500"
HighPrice="24.7800" LowPrice="24.0000" MaxPrice="24.7800" MinPrice="24.0000" Volume="16238302"
AskSize="105597" BidSize="97618" AskPrice="24.1600" BidPrice="24.1500" Symbol="BAC.NY"
MarketTime="12:08:41.356" Message="L1DB"/>
</Content>
</Response>
And then my main script:
<?php
$result = file_get_contents("lvl1.xml");
// echo $result;
$xml = new SimpleXMLElement($result);
// $dom = new DOMDocument();
// $dom->loadXML("lvl1.xml");
// $vol = dom->getElementsByTagName('Level1Data');
$vol=$xml->children->children('Level1Data');
$id = $xml["Volume"];
echo $id;
?>
Nothing gets returned and I am having a hard time reading the php documentation and their examples.
Thank you.
You can try to find the XML node using attributes() and foreach what attribute you want as per your requirements. If you need only single attribute then discard foreach looping.
<?php
$result =<<<EOT
<Response>
<Content>
<Level1Data Tick="U" Currency="USD" TickSize="0.0001000000" TickValue="0" AssetClass="Equity" InstrumentState="Open" LastPrice="24.1550" LotSize="10"
MinPermittedPrice="0" MaxPermittedPrice="0" ClosePrice="24.0300" OpenPrice="24.1500" FirstPrice="24.1500"
HighPrice="24.7800" LowPrice="24.0000" MaxPrice="24.7800" MinPrice="24.0000" Volume="16238302"
AskSize="105597" BidSize="97618" AskPrice="24.1600" BidPrice="24.1500" Symbol="BAC.NY"
MarketTime="12:08:41.356" Message="L1DB"/>
</Content>
</Response>
EOT;
$volume = '';
$xml = new SimpleXMLElement($result);
foreach($xml->Content->Level1Data[0]->attributes() as $a => $b) {
if($a=='Volume'){
$volume = $b;
}
}
echo $volume;
?>
Demo https://eval.in/839942
OR for single attribute e.g Volume
echo $xml->Content->Level1Data[0]->attributes()->Volume;
If you want to pickup Volume only, it can also be done as follows.
<?php
$result = <<<EOM
<Response>
<Content>
<Level1Data Tick="U" Currency="USD" TickSize="0.0001000000" TickValue="0" AssetClass="Equity" InstrumentState="Open" LastPrice="24.1550" LotSize="10"
MinPermittedPrice="0" MaxPermittedPrice="0" ClosePrice="24.0300" OpenPrice="24.1500" FirstPrice="24.1500"
HighPrice="24.7800" LowPrice="24.0000" MaxPrice="24.7800" MinPrice="24.0000" Volume="16238302"
AskSize="105597" BidSize="97618" AskPrice="24.1600" BidPrice="24.1500" Symbol="BAC.NY"
MarketTime="12:08:41.356" Message="L1DB"/>
</Content>
</Response>
EOM;
$xml = new SimpleXMLElement($result);
echo $xml->Content->Level1Data[0]->attributes()->Volume;
EDIT
<?php
$result = <<<EOM
<Response>
<Content>
<Level1Data Tick="U" Currency="USD" TickSize="0.0001000000" TickValue="0" AssetClass="Equity" InstrumentState="Open" LastPrice="24.1550" LotSize="10"
MinPermittedPrice="0" MaxPermittedPrice="0" ClosePrice="24.0300" OpenPrice="24.1500" FirstPrice="24.1500"
HighPrice="24.7800" LowPrice="24.0000" MaxPrice="24.7800" MinPrice="24.0000" Volume="16238302"
AskSize="105597" BidSize="97618" AskPrice="24.1600" BidPrice="24.1500" Symbol="BAC.NY"
MarketTime="12:08:41.356" Message="L1DB"/>
</Content>
</Response>
EOM;
$xml = new SimpleXMLElement($result);
function recur($obj){
if ( in_array('Level1Data', array_keys( (array) $obj->children()) ) === false){
recur($obj->children());
}else{
var_dump($obj->children()->Level1Data);
exit;
}
}
recur($xml);
My XML file is such as (for example):
<?xml version="1.0" encoding="UTF-8" ?>
<bikes>
<bike>
<model>First</model>
<speedNumber>4</speedNumber>
<sizes>100</sizes>
<amount>100</amount>
</bike>
<bike>
<model>Second</model>
<speedNumber>3</speedNumber>
<sizes>300</sizes>
<amount>150</amount>
</bike>
<bike>
<model>Third</model>
<speedNumber>4</speedNumber>
<sizes>300</sizes>
<amount>300</amount>
</bike>
</bikes>
How can I get child elements for the first <bike> element only?
I want to print model=First, speedNumber=4 ...
<bike>
<model>First</model>
<speedNumber>4</speedNumber>
<sizes>100</sizes>
<amount>100</amount>
</bike>
I tried this:
foreach ($xml->children(0) as $bikes)
{
foreach ($bikes->children() as $childs)
{
echo $childs->getName()."=".$childs ." ";
}
echo "<br>";
}
But it doesn't work for me.
How can I solve this problem?
You can access the elements directly using array syntax:
$bikes->bike[0]->model
$bikes->bike[0]->speedNumber
...
Full code:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<bikes>
<bike>
<model>First</model>
<speedNumber>4</speedNumber>
<sizes>100</sizes>
<amount>100</amount>
</bike>
<bike>
<model>Second</model>
<speedNumber>3</speedNumber>
<sizes>300</sizes>
<amount>150</amount>
</bike>
<bike>
<model>Third</model>
<speedNumber>4</speedNumber>
<sizes>300</sizes>
<amount>300</amount>
</bike>
</bikes>
XML;
$bikes = new SimpleXMLElement($xml);
echo $bikes->bike[0]->model . "\n";
echo $bikes->bike[0]->speedNumber . "\n";
echo $bikes->bike[0]->sizes . "\n";
echo $bikes->bike[0]->amount . "\n";
?>
Tested here: http://codepad.org/yVAyoPtG
In a php script how to read and convert a XML document to an object and access the obtained object in order to get his data?
<?php
$xml ='<?xml version="1.0" encoding="UTF-8" ?>
<data request-id="ID">
<data name="Name1"
d1="0"
d2="0231234"
d3="32584">
<data name="Name2"
d4="231234"
d5="2012-06-06 18:18:10.000607"
d6="3b048653-aaa9-485b-b0dd-d16e068230e9" />
</data>
</data>';
$xml = simplexml_load_string($xml);
//how to get the data d1? or d4? from the obtained object
?>
You can use this snippet:
<?php
$xmlstring = file_get_contents($filename);
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$object = json_decode($json);
Try using this function -
$xml ='<?xml version="1.0" encoding="UTF-8" ?>
<data request-id="ID">
<data name="Name1"
d1="0"
d2="0231234"
d3="32584">
<data name="Name2"
d4="231234"
d5="2012-06-06 18:18:10.000607"
d6="3b048653-aaa9-485b-b0dd-d16e068230e9" />
</data>
</data>';
function xmlToArray($input, $callback = null, $recurse = false) {
$data = ((!$recurse) && is_string($input))? simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA): $input;
if ($data instanceof SimpleXMLElement) $data = (array) $data;
if (is_array($data)) foreach ($data as &$item) $item = xmlToArray($item, $callback, true);
return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
$xml = xmlToArray($xml);
echo $xml['data']['#attributes']['d1'];
echo '<br/>';
echo $xml['data']['data']['#attributes']['d4'];
Use
$myxml = simplexml_load_string($xml);
echo $myxml->data[1]['d1'];
echo $myxml->data[1]['d2'];
echo $myxml->data[1]['d3'];
echo $myxml->data[2]['d4'];
Reference : How to parse XML with PHP5
try :-
echo $xml['data']['#attributes']['d1'];
echo '<br/>';
echo $xml['data']['data']['#attributes']['d4'];
I am trying to edit some XML with PHP. Currently the XML looking something like:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Main Title</title>
<link>http://exmaple.com</link>
<description> blahblahblah </description>
<language>en</language>
<item>
<title>Tite1</title>
<link>http://www.example.com (THIS IS WHAT I WANT)</link>
<description>blah blah blah</description>
</item>
.
.
.
</channel>
</rss>
I've tried to access the 2nd level link but my code only changes the first Link node value. Here is the code:
$xml->load('http://www.google.com/doodles/doodles.xml');
$element = $xml->getElementsByTagName('channel')->item(0);
$secondlvl = $element->getElementsByTagName('item')->item(0);
$2ndlevellinknode = $element->getElementsByTagName('link')->item(0);
$2ndlevellinknode->nodeValue = $newvalue;
Any suggestions? Also is it possible to use this line of code in a for loop like this
for ($i = 0; $i <= 20; $i++) {
$element = $xml->getElementsByTagName('channel')->item(0);
$secondlvl = $element->getElementsByTagName('item')->item(0);
$2ndlevellinknode = $element->getElementsByTagName('link')->item($i);
$2ndlevellinknode->nodeValue = $newvalue;
}
this should give you an idea.
$f = simplexml_load_file('test.xml');
print $f->channel->title . "\n";
print $f->channel->link . "\n";
print $f->channel->description . "\n";
foreach($f->channel->item as $item) {
print $item->title . "\n";
}