开发者

Simple xml update with php

I know this discussion has already been covered, and I've tried every suggestion on here, but I can't seem to get a simple read out of an xml file from php. I'm simply trying to read a tag's contents by id. Here's the xml:

test.xml

<?开发者_如何学JAVAxml version="1.0" encoding="UTF-8"?>
<queries>
    <sql id="one">here is the first one</sql>
    <sql id="two">here is the second one</sql>
</queries>

And I'm simply trying to read with this:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = TRUE;
$dom->loadXML('test.xml');
$node = $dom->getElementById('one');
echo $node->nodeValue;
?>

Why in the world can't I get this to work? Sorry for the newb question, but I'm brand new to php.


You need to set ID attributes with DOMElement::setIDAttribute or use a DTD which defines an attribute to be of type ID (which your example doesn't include).

Final code:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = TRUE;
$dom->loadXML('test.xml');
$dom->setIdAttribute("id",true);
$node = $dom->getElementById('one');
echo $node->nodeValue;
?>


getElementById() doesn't work the same in PHP as it does in JavaScript and the documentation will explain. If you don't want to go to the trouble of setting your IDs in code, an alternate way to "find by ID" is using XPath:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = TRUE;
$dom->loadXML('test.xml');

$dxp = new DOMXPath($dom);
$result = $dxp->query('//sql[@id = "one"]');
$node = $result->item(0);
echo $node->nodeValue;
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜