I've used the following code to do an XSLT in php:
# LOAD XML FILE
$XML = new DOMDocument();
$XML = simplexml_load_file("images/upload/source.xml");
# START XSLT
$xslt = new XSLTProcessor();
$XSL = new DOMDocument();
$XSL->load( 'xsl/transfer.xsl', LIBXML_NOCDATA);
$xslt->importStylesheet( $XSL );
#PRINT
print $XML->saveXML();
print $XML->save("newfile.xml") ;
The code is quite straightforward, we need to load the source xml file and then load up the stylesheet, and indeed it actually works.
The code that causes trouble is the last line:
print $XML->save("newfile.xml") ;
after running which I got error "Fatal error: Call to undefined method SimpleXMLElement::save() ". But, actually ,I was following a tutorial here:
http://devzone.zend.com/article/1713.
Maybe I screwed up something, could anybody give me a hint? thanks in advance.
Following your guys' advice, I modified the code like this:
# LOAD XML FILE
$XML = new DOMDocument();
$XML->load("images/upload/source.xml");
# START XSLT
$xslt = new XSLTProcessor();
$XSL = new DOMDocument();
$XSL->load( 'xsl/transfer.xsl', LIBXML_NOCDATA);
$xslt->importStylesheet( $XSL );
#PRINT
print $xslt->transformToXML( $XML );
now the correctly-transformed XML gets shown in the browser, I've tried some ways but still couldn't figure out how to print this result to a file instead of showing in the browser, any help is appreciated, thanks in advance.
You're changing how $XML is defined, simply call the load method on $XML instead of simplexml_load_file:
$XML = new DOMDocument();
$XML->load("images/upload/source.xml");
There's no reason at all to use simplexml since the XSLT processing is all done with DOMDocument. So just replace that one line, and you should be good to go...
$XML = new DOMDocument();
$XML = simplexml_load_file("images/upload/source.xml");
First you store a DOMDocument in $XML, and then you replace it with a SimpleXMLElement. DOMDocument does have a save method, but SimpleXMLElement does not.
Admission: didn't look at the tutorial, so I don't know why/if that one works.
$XML = new DOMDocument();
$XML = simplexml_load_file("images/upload/source.xml");
You're saying that $XML is a DOMDocument and then you replace it with a SimpleXMLElement on line 2
Use
$XML = new DOMDocument();
$XML->load("images/upload/source.xml");
instead
Problem:
$XML = new DOMDocument();
$XML = simplexml_load_file("images/upload/source.xml");
You create a DOMDocument, which you then overwrite with a SimpleXMLElement object. The first line is dead code. You aren't using it at all, since you overwrite it in the next statement.
save is a method in DOMDocument. asXML($file) is the equivalent for SimpleXML (or saveXML($file) which is an alias.
If you look at the tutorial, it's clearly:
$xsl = new DomDocument();
$xsl->load("articles.xsl");
$inputdom = new DomDocument();
$inputdom->load("articles.xml");
So, if you use simplexml_load_file, then you're not really following the tutorial.
Related
After googling could not found anything related to my issue.
Problem is: I parse page, find one table [there is four tables].
And when I found, I want to add one/some row/rows to table. But I don`t know how to do it. Some similar issues are about parsing xml and viewing content.
In code I have something like this:
$dom = new DOMDocument();
$dom->loadHTML($output->getHTML());
$xpath = new DOMXPath($dom);
$tableProp = $xpath->query('//*[#class="smwb-factbox"][2]');
....
$dom->asHTML();
Solution is simple:
With set of methods such as createElement, setAttribute and appendChild I solved my problem, example as follows:
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($output->getHTML(), 'HTML-ENTITIES', 'utf-8'));
$xpath = new DOMXPath($dom);
$tableProp = $xpath->query('//*[#class="smwb-factbox"][2]');
...
$th_el = $dom->createElement('th', $th_outer_inner_span_a_el);
...
$td_el = $dom->createElement('td', '');
$td_el->appendChild($td_el_outer_span);
$tr_el = $dom->createElement('tr', '');
$tr_el->setAttribute('class', 'smwb-propvalue');
$tr_el->appendChild($th_el);
$tr_el->appendChild($td_el);
$tableProp->item(0)->appendChild($tr_el);
$dom->saveHTML();
...
The idea is pretty simple.
I have table in mediawiki, find it, create new row and insert it, after save it. That's all.
So my XML Looks like this :-
<ns0:ASN xmlns:ns0="http://schemas.microsoft.com/dynamics/2008/01/documents/ASN" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns0:CustPackingSlipJour class="entity">
<ns0:BON_FileNameSeqNum>40</ns0:BON_FileNameSeqNum>
<ns0:BON_TotalNetAmount>10.00</ns0:BON_TotalNetAmount>
<ns0:BON_TotalTaxAmount>.00</ns0:BON_TotalTaxAmount>
<ns0:InvoiceAccount>Acc</ns0:InvoiceAccount>
<ns0:LanguageId>EN</ns0:LanguageId>
<ns0:OrderAccount>I</ns0:OrderAccount>
<ns0:PurchaseOrder>74</ns0:PurchaseOrder>
<ns0:Qty>13.00</ns0:Qty>
<ns0:SalesId>00025873_054</ns0:SalesId>
<ns0:CustPackingSlipTrans class="entity">
<ns0:BON_LineNetAmount>19.00</ns0:BON_LineNetAmount>
<ns0:BON_SalesPrice>0.00</ns0:BON_SalesPrice>
<ns0:DeliveryDate>2016-11-30</ns0:DeliveryDate>
<ns0:ItemId>25712</ns0:ItemId>
<ns0:Ordered>1.00</ns0:Ordered>
<ns0:PackingSlipId>00339_061</ns0:PackingSlipId>
<ns0:Qty>1.00</ns0:Qty>
</ns0:CustPackingSlipTrans>
<ns0:CustPackingSlipTrans class="entity">
<ns0:BON_LineNetAmount>19.00</ns0:BON_LineNetAmount>
<ns0:BON_SalesPrice>0.00</ns0:BON_SalesPrice>
<ns0:DeliveryDate>2-11-30</ns0:DeliveryDate>
<ns0:ItemId>25823-35714</ns0:ItemId>
<ns0:Ordered>1.00</ns0:Ordered>
<ns0:PackingSlipId>00_061</ns0:PackingSlipId>
<ns0:Qty>1.00</ns0:Qty>
</ns0:CustPackingSlipTrans>
</ns0:CustPackingSlipJour>
</ns0:ASN>
How can I access the value of ItemId for all CustPackingSlipTrans ?
I have tried various ways of getting it, for instance registering xpath and then trying to access. However, it ins't working for me. Whats the best way to get it's value?
The solution using DOMXPath::query method:
// $xml contains your xml contents
$doc = new \DOMDocument();
$doc->loadXML($xml);
$xpath = new \DOMXPath($doc);
foreach ($xpath->query("ns0:CustPackingSlipJour/ns0:CustPackingSlipTrans/ns0:ItemId") as $node) {
var_dump($node->nodeValue);
}
The output:
string(5) "25712"
string(11) "25823-35714"
DEMO
You need to register the namespace with the DomXPath:
$xp = new DomXPath ($doc);
$xp->registerNamespace ('pfx', 'http://pfxuri');
I'm trying to parse an xml data that I'm getting via an api call. I can use file_get_contents to read into a string but simpleXML_load_string seems to fail to read it. I can save it to a file and then simpleXML_load_file works. But I would rather not write the contents to a file. I can't seem to understand how to use DOM or XMLParse with this either. I'm new to PHP and parsing XML. The output data from the api call is below.
<Search>
<DS_Rating>DS3</DS_Rating>
<Overall>17.5</Overall>
<LargestGiftLow>0</LargestGiftLow>
<LargestGiftHigh>0</LargestGiftHigh>
<EstimatedCapacityRange>I - $15,000 - $24,999</EstimatedCapacityRange>
<EstimatedCapacity>20452</EstimatedCapacity>
<RealEstateEst>270073</RealEstateEst>
<RealEstateCount>1</RealEstateCount>
<LikelyMatchesCount>0</LikelyMatchesCount>
<LikelyMatchesTotal>0</LikelyMatchesTotal>
<FndBoard></FndBoard>
<GSBoard></GSBoard>
<PoliticalLikelyCount>0</PoliticalLikelyCount>
<PoliticalLikelyTotal>0</PoliticalLikelyTotal>
<BusinessRevenues>0</BusinessRevenues>
<SECStockValue>0</SECStockValue>
<SECInsider></SECInsider>
<MarketGuide></MarketGuide>
<IRS990PF></IRS990PF>
<RealEstateTrust></RealEstateTrust>
<MarketGuideComp>0</MarketGuideComp>
<MarketGuideOptions>0</MarketGuideOptions>
<BusinessAffiliation></BusinessAffiliation>
<Pension></Pension>
<PensionAssets>0</PensionAssets>
<CorpTech></CorpTech>
<Pilot></Pilot>
<AirplaneOwner></AirplaneOwner>
<Boat></Boat>
<submit_time>2014-03-11 15:48:45</submit_time>
</Search>
Figured out that the issue was that what I was seeing in the browser was actually a php output with html_entiity encoded. I was able to process it with the code below which let me load it with simplexml.
$rawxml = html_entity_decode($rawxml);
$rawxml = str_replace(array(' ', "<pre>"), '', $rawxml);
$rawxml = utf8_encode($rawxml);
$xml = simplexml_load_string($rawxml);
If you XML is in a file use
simplexml_load_file
if you have it in a string use
simplexml_load_string
Then you can use the following code to access it.
<?php
$yourxml = simplexml_load_file('your.xml');
echo $yourxml->search[0]->DS_Rating;
?>
This would then output
DS3
to the browser via the 'echo' in your code. I hope this points you in the correct direction.
Try to use this:
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?>'.$yourXMLString);
In DOM you load the XML into a DOMDocument and create a DOMXpath instance for it.
$dom = new DOMDocument();
$dom->loadXml($xmlString);
//$dom->load($xmlFile);
$xpath = new DOMXpath($dom);
DOMXpath::evaluate() is used to fetch data from the DOM.
$rating = $dom->evaluate('string(/Search/DS_Rating)');
An Xpath expression like /Search/DS_rating always returns a node list. You can use foreach() to iterate it. The string() function in Xpath takes the first node from the list and casts it into a string. If here is not node in the list the result is an empty string.
$xmlString = <<<'XML'
<Search>
<DS_Rating>DS3</DS_Rating>
<Overall>17.5</Overall>
</Search>
XML;
$dom = new DOMDocument();
$dom->loadXml($xmlString);
$xpath = new DOMXpath($dom);
var_dump(
$xpath ->evaluate('string(/Search/DS_Rating)')
);
Output: https://eval.in/118921
string(3) "DS3"
I want a list of xml node in a given xml node. The code sample below should do it? (but doesn't)
$doc= new DOMDocument("1.0", "UTF-8");
$rootel = $doc->createElement("drobj");
$el1 = $doc->createElement("el1");
$rootel->appendChild($el1);
$el2 = $doc->createElement("el2");
$rootel->appendChild($el2);
$doc->appendChild($rootel);
$doc->saveXML();
Result is
<drobj>
<el1>
<el2></el2>
</el1>
</drobj>
I expected
<drobj>
<el1></el1>
<el2></el2>
</drobj>
$doc= new DOMDocument("1.0", "UTF-8");
$rootel = $doc->createElement("drobj");
$el1 = $doc->createElement("el1");
$rootel->appendChild($el1);
$el2 = $doc->createElement("el2");
$rootel->appendChild($el2);
$doc->appendChild($rootel);
$doc->save("test.xml");
This works perfectly fine. I tested it out.
The only thing i changed was the last line to save the xml to a file.
I'm trying to write a script that grabs the URL of the first image from this website: http://www.slothradio.com/covers/?adv=&artist=pantera&album=vulgar+display+of+power
Here's my script:
$content = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($content);
$xpath = new DOMXpath($doc);
$elements = $xpath->query("*/div[#class='album0']/img");
echo '<pre>';print_r($elements);exit;
When I run that, it outputs
DOMNodeList Object
(
)
Even when I change my query to $xpath->query("*/img"), I still get nothing. What am I doing wrong?
$doc->loadHTMLFile($content); takes in FILE PATH not HTML content see documentation
http://php.net/manual/en/domdocument.loadhtmlfile.php
Use
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
To Output Element use
var_dump(iterator_to_array($elements));
//Or
print_r(iterator_to_array($elements));
Thanks
:)
What am I doing wrong?
You are using print_r, but DOMNodeList does not offer any output for that function (because it's an internal class). You can start with outputting the number of items for example. In the end you need to iterate over the node list and deal with each node on your own.
printf("Found %d element(s).\n", $elements->length);