开发者

I need to get xml with php. How would I go about that? [closed]

开发者 https://www.devze.com 2022-12-21 20:24 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in开发者_如何转开发 its current for
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in开发者_如何转开发 its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

What is the best way?


SimpleXML and the PHP DOM are good bets.


Use SimpleXML. It turns an XML document into an object that provides structured access to the XML.

To create a SimpleXML object from an XML document stored in a string, pass the string to simplexml_load_string( ). It returns a SimpleXML object.

As an example consider this:

$channel =<<<_XML_
<channel>    
 <title>Example title</title>    
 <link>http://example.com/</link>    
 <description>Example desccription</description>    
</channel>    
_XML_;
// The XML that needs to be parsed

$xml = simplexml_load_string($channel); // create a SimpleXML object.

print "The $xml->title channel is available at $xml->link. ";

will print:

The Example title is available at http://example.com/.


You can use the following program also for creating the SimpleXml object. Using SimpleXml object you can access the xml tags.

test.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<employee>

        <name> Shyam </name>
        <age> 20 </age>
        <place> Chennai </place>
</employee>

file.php

<?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach($xml->children() as $child)
          {
            echo $child->getName() . ": " . $child . "<br />";
          }
?>


By "get XML", do you mean retrieve it from a remote source, or parse a XML text that you already have?

For the former, either use PHP's built-in capability to load URL content (via the file_get_contents or similar functions applied to URLs), or use a library like cURL (which is included standard with most PHP distributions).

For the latter, libraries like SimpleXML (also included standard) can be quite useful.

0

精彩评论

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

关注公众号