XML and PHP printing out specifics
Im new to XML and decided I would try and use it to implement a simple CMS compared to constructing a whole MySQL database. However Im stuck on how to print things out on the webpage. In all tutorials I've seen they loop through each XML element and print out every one, I only want to print out the one where page name = home or page name = mypage.
This is simply done in MySQL with WHERE page["home"], but I cant find what the same code using XML is.
<?xml version="1.0" encoding="utf-8"?>
<content>
<page name = "home"><br />
<title>Home</title><br />
<subtitle>a test of my testing</subtitle&开发者_C百科gt;<br />
<top-papa>blah blah top para</top-papa><br />
<mid-para>blah blah mid para</mid-para><br />
<bot-para>blah blah bot para</bot-para><br />
<image>
<imge>mememem</imge><br />
</image>
</page>
<page name = "whatdowedo"><br />
<title>What do we do?</title><br />
<subtitle>a test of my testing</subtitle><br />
<top-papa>blah blah top para</top-papa><br />
<mid-para>blah blah mid para</mid-para><br />
<bot-para>blah blah bot para</bot-para><br />
<image>
<imge>mememem</imge><br />
</image>
</page>
</content>
Many thanks to all replies. Ben
You could use XPath queries on your XML document.
For example, if you have your XML in a string :
$str = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<content>
...
</content>
XML;
And load it using simplexml_load_strin()
:
$xml = simplexml_load_string($str);
You can then use the SimpleXMLElement::xpath()
method to do an XPath query on that XML document -- searching, for example, by value of the name
attribute :
$nodes = $xml->xpath('//page[@name="home"]');
if (count($nodes) > 0) {
echo (string)$nodes[0]->title;
}
And, in this specific case, you'd get the following output :
Home
Note : the same kind of thing is, of course, possible with DOMDocument
, and DOMXpath
.
To retrieve the XML of the page home like so:
Home:
<page name="home"><br/>
<title>Home</title><br/>
<subtitle>a test of my testing</subtitle><br/>
<top-papa>blah blah top para</top-papa><br/>
<mid-para>blah blah mid para</mid-para><br/>
<bot-para>blah blah bot para</bot-para><br/>
<image>
<imge>mememem</imge><br/>
</image>
</page>
you can do with the simplexml quite quickly (Demo):
$xml = simplexml_load_string($str);
$name = 'home';
$xpath = sprintf("/content/page[@name='%s'][1]", $name);
$page = $xml->xpath($xpath);
if (!$page) {
throw new Exception(sprintf('Page "%s" not found.', $name));
}
list($page) = $page;
echo $page->title, ":\n";
echo $page->asXML();
精彩评论