Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

php domdocument 使用一个url来读取文档应该怎么读

因为项目需要,我需要使用php对xml上的值进行修改。使用的DOMdocument来做。
代码如下

      $xmlpatch ='http://www.*****.com/vr/wtest/vtour/tour.xml';
        $xml = simplexml_load_file($url);
        $doc = new DOMDocument();   
        $doc -> formatOutput = true;  
        if($doc -> load($xmlpatch)) {   
        $root = $doc -> documentElement;   
        $elm = $root -> getElementsByTagName('scene');   
        $hotspot = $elm[1] ->getElementsByTagName('hotspot');
        $hotspot[0] ->setAttribute('videourl',$videourl1);
        $hotspot[1] ->setAttribute('onclick',$videourl2);
    
    
        $doc->save($xmlpatch);
        } 

代码应该是没问题的,问题出在我原来$xmlpatch写的是相对路径,因为用的在本地用的环境包,所以没问题。
但是服务器上的环境php文件和xml是跨域放的,于是我换成了绝对路径。但是发现脚本失效了。上网有人建议使用simplexml来做。但是我实验一下确实能读出来,但是我没在w3cschool上找到修改属性的函数。
求各位大神帮帮忙~不胜感激~能告诉我simplexml怎么修改属性,或者domdocument怎么用url来读都好。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

先用 curl 读取 xml 文件的信息,再用 DOMdocument 或者 simplexml 处理。

<?php

$url = 'http://www.abc.com/sitemap.xml';

$header = array(
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
    'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
    'Accept-Encoding: gzip, deflate',
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$data = curl_exec($curl);
curl_close($curl);

if ($xml = simplexml_load_string($data)) {
    $xml->row->name = 'new_name'; // Edit XML Object node
    echo $xml->asXML();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...